
DosEquiz.java
public?class?DosEquis
{
????public?static?void?main(String[]?args)
????{
????????char?x?=?'X';
????????int?i?=?89;
????????final?int?j?=?89;
????????final?int?k?=?6666666;
????????System.out.println(true???x?:?88);??//?X
????????System.out.println(false???i?:?x);?//?88
????????
????????System.out.println(true???j?:?x);?//?Y
????????System.out.println(false???j?:?x);?//?X
????????System.out.println(true???k?:?x);??//?6666666
????????System.out.println(false???k?:?x);??//?88
????????
????????
????????//System.out.println((true???true?:?new?Boolean(true)).booleanValue());?\\?a?compile-time?error?
????????//System.out.println((true???false?:?new?Boolean(true)).booleanValue());?\\?a?compile-time?error?
????????System.out.println(new?Boolean((true???true?:?new?Boolean(true))).booleanValue());?//ok
????????
????????//Double?aInt?=?true???new?Integer(1)?:?null;?--?a?compile-time?error?
????????//Double?aInt?=?false???new?Integer(1)?:?null;?--?a?compile-time?error?
????????
????????
????}
}
這個謎題是關于
Conditional Operator ? :[JLS 15.25]。
1、Conditional Operator 有三個運算符表達式,第一個必須是 boolean或 Boolean型的,否則引發一個compile-time error 。
2、一個 Conditional Expression的類型T是由第二個表達式 T2和第三個表達式T3的類型來決定的。具體規則如下:
- rule 1:? 如果T2 == T3(包括T2 == T3 == null的情況),那么 T = T2(T3)。
- rule 2:? 如果 T2與T3這兩個之中有一個是boolean型,另外一個是Boolean型,那么 T = boolean。
- rule 3:? 如果T2與T3之中有一個是null類型,而另外一個是一個引用類型(reference type) RT,那么T = RT
- 如果T2與T3是可以轉化成數值類型的,那么結果有以下幾種情況:
- rule 4:? 如果T2與T3有一個是byte或者Byte,另一個是short或者Short,那么T = short
- rule 5:? 如果T2與T3中有一個是 GT 型,這里 GT 泛指byte, short, char中的任何一個, 而且另一個是一個int型的常量表達式(注意,必須是一個 int型的constant expression),而且 該常量表達式可以用GT表示(即不會產生精度損失的情況,個人的理解^_^),則T=GT。
- rule 6: 如果T2和T3有一個是Byte型,另一個是可以用byte型表示的int型常量表達式,那么T=byte
- rule 7: 如果T2和T3有一個是Short型,另一個是可以用byte型表示的int型常量表達式,那么T=short
- rule 8: 如果T2和T3有一個是Character型,另一個是可以用char型表示的int型常量表達式,那么T=char
- rule 9:? Otherwise, binary numeric promotion (JLS 5.6.2) is applied to the operand
types, and the type of the conditional expression is the promoted type of the
second and third operands. Note that binary numeric promotion performs unboxing
conversion (JLS 5.1.8)
and value set conversion (JLS 5.1.13).(這個很多詞語都不知該怎么翻譯,就直接copy過了。。。)
rule 10:? Otherwise, the second and third operands are of types S1 and S2 respectively.
Let T1 be the type that results from applying
boxing conversion to S1, and let T2 be the type that results from applying boxing
conversion to S2. The type of the conditional
expression is the result of applying capture conversion (JLS 5.1.10) to lub(T1, T2) (JLS 15.12.2.7).