2

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

but subtracting like this: char c = 'b'-'a'; doesn't make any error! why is not that working like int then?
@agassaa Because your example in your comment is computed at compilation time.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.