2009-06-10 72 views
22

我找不到規範的相關部分來回答這個問題。 在Java中的條件運算符語句中,是否評估了真和假參數?爪哇三元(立即如果)評估

所以可以在下面拋出NullPointerException

Integer test = null; 

test != null ? test.intValue() : 0; 
+3

這也是一些簡單的東西,你可以試試看看會發生什麼:) – 2009-06-10 21:53:32

+7

這給你一個特定實例的信息。最好找到標準說的。 – 2009-06-10 21:56:50

回答

43

既然你想要的規格,這裏是(從§15.25 Conditional Operator ? :,該段的最後一句):

The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.

8

不,這不可能。這是因爲相同的:

Integer test = null; 
if (test != null) { 
    test = test.intValue(); 
} 
else { 
    test = 0; 
} 
0

的語法是錯誤的。

Integer test =(test!= null)? test.intValue():0;

希望它可以幫助....

+1

在同一行聲明和引用變量? *「錯誤:變量`test`可能沒有初始化」* – Pang 2016-11-25 01:37:55

7

我知道這是舊的文章,但看非常相似的情況下,再投我:P

回答原來的問題:只有一個操作數是評價,但:

@Test 
public void test() 
{ 
    Integer A = null; 
    Integer B = null; 

    Integer chosenInteger = A != null ? A.intValue() : B;  
} 

這個測試總是會拋出NullPointerException,在這種情況下,IF statemat不等於?:操作符。

原因是這裏http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25。關於拳擊/拆箱的部分被捲入,但它可以很容易理解看:

"If one of the second and third operands is of type boolean and the type of the other is of type Boolean , then the type of the conditional expression is boolean ."

這同樣適用於Integer.intValue()

最好的問候!