public class Ternary {
public static void main(String[] args) {
char x = 'X';
int i = 0;
System.out.println(true ? x : 0);
System.out.println(false ? i : x);
}
}
ternary operator
的规则https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
第一个是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.
的结果
在这种情况下,T为字符类型,并且常量表达式为0
所以输出是char类型,它是x
Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
的情况在此处https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2了解有关二进制数值的促销信息>>
第2点的最后一种情况在这里适用
Otherwise, both operands are converted to type int.
并将char转换为int给出其ascii值,该值为88因此输出为88