In java if “char c = 'a' ” why does “c = c

2020-04-14 08:54发布

问题:

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.

回答1:

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.


回答2:

First you are declaring c as char than you are using it as an int