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.
c + 1
is anint
, as the operands undergo binary numeric promotion:c
is achar
1
is anint
so
c
has to be widened toint
to make it compatible for addition; and the result of the expression is of typeint
.As for the things that "work":
c = (char)(c + 1)
is explicitly casting the expression tochar
, so its value is compatible with the variable's type;c += 1
is equivalent toc = (char) ((c) + (1))
, so it's basically the same as the previous one.c++
is of typechar
, so no cast is required.First you are declaring c as char than you are using it as an int