agassaa agassaa - 11 days ago 7
Java Question

How does String charAt() method work in Java?

Why does the following code create compile error? Doesn't

charAt()
method return
char
datatype?

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

Answer

When you subtract two chars, they are promoted to int and the subtraction is performed on two int operands, and the result is an int.

You can cast to char to assign the result to a char :

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'.

Comments