[英]Java ternary (immediate if) evaluation
I can't find the relevant portion of the spec to answer this. 我无法找到规范的相关部分来回答这个问题。 In a conditional operator statement in Java, are both the true and false arguments evaluated?
在Java中的条件运算符语句中,是否评估了true和false参数?
So could the following throw a NullPointerException 因此,以下内容可能会抛出NullPointerException
Integer test = null;
test != null ? test.intValue() : 0;
Since you wanted the spec, here it is (from §15.25 Conditional Operator ? : , the last sentence of the section): 既然你想要规范,这里是(来自§15.25条件运算符?: ,该节的最后一句):
The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
未针对条件表达式的特定评估评估未选择的操作数表达式。
I know it is old post, but look at very similar case and then vote me :P 我知道这是老帖子,但看看非常相似的情况,然后投票给我:P
Answering original question : only one operand is evaluated BUT: 回答原始问题:只评估一个操作数但是:
@Test
public void test()
{
Integer A = null;
Integer B = null;
Integer chosenInteger = A != null ? A.intValue() : B;
}
This test will throw NullPointerException
always and in this case IF statemat is not equivalent to ?: operator. 此测试将始终抛出
NullPointerException
,在这种情况下,IF statemat不等同于?:operator。
The reason is here http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25 . 原因在于http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25 。 The part about boxing/unboxing is embroiled, but it can be easy understood looking at:
关于装箱/拆箱的部分是卷入其中的,但是可以很容易地理解:
"If one of the second and third operands is of type
boolean
and the type of the other is of typeBoolean
, then the type of the conditional expression isboolean
."“如果第二个和第三个操作数之一是
boolean
类型,另一个类型是Boolean
类型,那么条件表达式的类型是boolean
。”
The same applies to Integer.intValue()
这同样适用于
Integer.intValue()
Best regards! 最好的祝福!
No, it couldn't. 不,它不能。 That's the same as:
这与以下相同:
Integer test = null;
if ( test != null ) {
test = test.intValue();
}
else {
test = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.