Why does the following code create compile error? Doesn't
public static void main (String args) throws java.lang.Exception
String a = "abcd";
char c = a.charAt(2)-'a';
error: incompatible types: possible lossy conversion from int to char
When you subtract two
chars, they are promoted to
int and the subtraction is performed on two
int operands, and the result is an
You can cast to
char to assign the result to a
char c = (char) (a.charAt(2)-'a');
Note that you might get unexpected results if the subtraction results in a negative value, since
char can't contain negative values.
Besides, I'm not sure it makes any sense to subtract 'a' from a character and store the result in a
char. In your example, it will give you the character whose numeric value is 2, which has no relation to the character 'c'.