Java 三元(立即如果)评估
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/978324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java ternary (immediate if) evaluation
提问by Mike Pone
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;
采纳答案by Michael Myers
Since you wanted the spec, here it is (from §15.25 Conditional Operator ? :, the last sentence of the section):
由于您想要规范,这里是(来自§15.25 Conditional Operator ? :,本节的最后一句):
The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
对于条件表达式的特定评估,不会评估未选择的操作数表达式。
回答by stevedbrown
No, it couldn't. That's the same as:
不,不能。这与:
Integer test = null;
if ( test != null ) {
test = test.intValue();
}
else {
test = 0;
}
回答by Micha? Króliczek
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 不等同于 ?: 运算符。
The reason is here 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:
原因在这里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 typeBoolean
, then the type of the conditional expression isboolean
."
“如果第二个和第三个操作数之一是 type
boolean
而另一个的类型是 typeBoolean
,则条件表达式的类型是boolean
。”
The same applies to Integer.intValue()
这同样适用于 Integer.intValue()
Best regards!
此致!