Java 三元(立即 if)求值
我找不到规范的相关部分来回答这个问题。 在 Java 的条件运算符语句中,是否同时评估 true 和 false 参数?
那么下面的代码是否会抛出 NullPointerException
Integer test = null;
test != null ? test.intValue() : 0;
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?
So could the following throw a NullPointerException
Integer test = null;
test != null ? test.intValue() : 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不可能。 这与:
No, it couldn't. That's the same as:
既然您想要规范,那就是(来自 §15.25 条件运算符 ? :,本节最后一句):
Since you wanted the spec, here it is (from §15.25 Conditional Operator ? :, the last sentence of the section):
我知道这是旧帖子,但看看非常相似的情况,然后投票给我:P
回答原始问题:仅评估一个操作数但是:
此测试将始终抛出
NullPointerException
,在这种情况下 IF statemat 是不等于 ?: 运算符。原因在这里 http://docs.oracle .com/javase/specs/jls/se5.0/html/expressions.html#15.25。 关于装箱/拆箱的部分很复杂,但看一下就很容易理解:
这同样适用于
Integer.intValue()
祝好!
I know it is old post, but look at very similar case and then vote me :P
Answering original question : only one operand is evaluated BUT:
This test will throw
NullPointerException
always and in this case IF statemat is not equivalent to ?: operator.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:
The same applies to
Integer.intValue()
Best regards!