2009-06-10 75 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()

最好的问候!