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

你说的曾经没有我的故事 提交于 2019-12-31 03:03:44

问题


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



来源:https://stackoverflow.com/questions/53260641/in-java-if-char-c-a-why-does-c-c-1-not-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!