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)
EVERY expression written in the Java programming language has a type that
can be deduced from the structure of the expression and the types of the literals,
variables, and methods mentioned in the expression. It is possible, however, to
write an expression in a context where the type of the expression is not appropriate.
In some cases, this leads to an error at compile time. In other cases, the context may
be able to accept a type that is related to the type of the expression; as a convenience,
rather than requiring the programmer to indicate a type conversion explicitly, the
Java programming language performs an implicit conversion from the type of the
expression to a type acceptable for its surrounding context.
The type conversion in your case that happens at compile time explains the output.
In the cases where i was involved, c has been promoted to integer.
In the cases where 0 was involved, it is treated as character and hence c remained as character.