
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?
????????
????????
????}
}
這個(gè)謎題是關(guān)于
Conditional Operator ? :[JLS 15.25]。
1、Conditional Operator 有三個(gè)運(yùn)算符表達(dá)式,第一個(gè)必須是 boolean或 Boolean型的,否則引發(fā)一個(gè)compile-time error 。
2、一個(gè) Conditional Expression的類型T是由第二個(gè)表達(dá)式 T2和第三個(gè)表達(dá)式T3的類型來決定的。具體規(guī)則如下:
- rule 1:? 如果T2 == T3(包括T2 == T3 == null的情況),那么 T = T2(T3)。
- rule 2:? 如果 T2與T3這兩個(gè)之中有一個(gè)是boolean型,另外一個(gè)是Boolean型,那么 T = boolean。
- rule 3:? 如果T2與T3之中有一個(gè)是null類型,而另外一個(gè)是一個(gè)引用類型(reference type) RT,那么T = RT
- 如果T2與T3是可以轉(zhuǎn)化成數(shù)值類型的,那么結(jié)果有以下幾種情況:
- rule 4:? 如果T2與T3有一個(gè)是byte或者Byte,另一個(gè)是short或者Short,那么T = short
- rule 5:? 如果T2與T3中有一個(gè)是 GT 型,這里 GT 泛指byte, short, char中的任何一個(gè), 而且另一個(gè)是一個(gè)int型的常量表達(dá)式(注意,必須是一個(gè) int型的constant expression),而且 該常量表達(dá)式可以用GT表示(即不會(huì)產(chǎn)生精度損失的情況,個(gè)人的理解^_^),則T=GT。
- rule 6: 如果T2和T3有一個(gè)是Byte型,另一個(gè)是可以用byte型表示的int型常量表達(dá)式,那么T=byte
- rule 7: 如果T2和T3有一個(gè)是Short型,另一個(gè)是可以用byte型表示的int型常量表達(dá)式,那么T=short
- rule 8: 如果T2和T3有一個(gè)是Character型,另一個(gè)是可以用char型表示的int型常量表達(dá)式,那么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).(這個(gè)很多詞語都不知該怎么翻譯,就直接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).