Consider this code snippet:
public static void main(String[] args) {
int z1 = 0;
final int z2 = 0;
System.out.println(false ? z1 : 'X');
System.out.println(false ? z2 : 'X');
}
When running this code, I would expect to see two X
in your console. However, the real output is:
88
X
If we take a look at the Java specifications regarding the ternary operator, we found that
If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
So the first output considers the 'X'
char as an int
, that's why it prints 88
.
However, I am not sure to understand why the use of final
changes the behavior for the second output.