日期:2014-05-20  浏览次数:20769 次

关于三元运算符的疑问!求指点
public class GenericTest{
public static void main(String[] args){
                char a = 'A';  
int i = 0;  
System.out.println(true ? 'A' : i);  
System.out.println(true ? 'A' : 0);
System.out.println(true ? a : i);
System.out.println(true ? a : 0);
System.out.println(false ? 0 : a);
System.out.println(false ? 0 : 'A');
System.out.println(false ? i : a);
System.out.println(false ? i : 'A');
}
}
【输出结果】
65
A
65
A
A
A
65
65
毫无规律啊,实在不能理解为什么是这些输出!求大神指教!三元运算符的转型规则!~
转型 三元运算符

------解决方案--------------------
The type of a conditional expression is determined as follows:
? If the second and third operands have the same type (which may be the null type),
then that is the type of the conditional expression.
? If one of the second and third operands is of primitive type T, and the type of the
other is the result of applying boxing conversion (§5.1.7) to T, then the type of
the conditional expression is T.
? If one of the second and third operands is of the null type and the type of the other
is a reference type, then the type of the conditional expression is that reference
type.
? Otherwise, if the second and third operands have types that are convertible
(§5.1.8) to numeric types, then there are several cases:
◆ If one of the operands is of type byte or Byte and the other is of type short