Can anyone explain this?
public class Test {
public static void main(String[] args) {
char c = 'A';
int i = 0;
boolean b = true;
System.out.println(b ? c : i);
System.out.println(b ? c : (char)i);
System.out.println(b ? c : 0);
System.out.println(b ? c : (char)0);
}
}
Output:
65
A
A
A
It sure looks strange from where I’m standing. I would have expected only As to print out. And moreover: how come when I substitute 0 for i the output changes? The output seems to be the same for all values of i, not just 0.
From the Java Language Specification, about type conversion and promotion (see the text in bold)
The type conversion in your case that happens at compile time explains the output.
In the cases where
iwas involved,chas been promoted to integer.In the cases where
0was involved, it is treated as character and hencecremained as character.