In java if "char c = 'a' " why does "c = c + 1" not compile?

רעי וייס ליפשיץ :

I tried to compile the following code:

public static void main(String[] args){
    for (char c = 'a'; c <='z'; c = c + 1) {
        System.out.println(c);
    }
}

When I try to compile, it throws:

Error:(5, 41) java: incompatible types: possible lossy conversion from int to char

The thing is, it does work if I write c = (char)(c + 1), c += 1 or c++.

I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1; but I see no way that the value of 'c' can pass 'char' type maximum in the original function.

Andy Turner :

c + 1 is an int, as the operands undergo binary numeric promotion:

  • c is a char
  • 1 is an int

so c has to be widened to int to make it compatible for addition; and the result of the expression is of type int.

As for the things that "work":

  • c = (char)(c + 1) is explicitly casting the expression to char, so its value is compatible with the variable's type;
  • c += 1 is equivalent to c = (char) ((c) + (1)), so it's basically the same as the previous one.
  • c++ is of type char, so no cast is required.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111377&siteId=1