Reputation: 145
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
Upvotes: 2
Views: 1228
Reputation: 172418
Java Language Specification says:
If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
So you need to explicitly cast it to char to get rid of the possible lossy error
char c = (char) (a.charAt(2)-'a');
Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
Upvotes: 1
Reputation: 393801
When you subtract two char
s, 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'.
Upvotes: 4
Reputation: 142
charAt() method return char type But you are subtracting two char that will return int value in this case it will be 2 . So receive it into int it will work.
int c = a.charAt(2)-'a';
Upvotes: 0