Java ternary (immediate if) evaluation

假如想象 提交于 2019-11-27 04:46:06
Michael Myers

Since you wanted the spec, here it is (from §15.25 Conditional Operator ? :, the last sentence of the section):

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

Michał Króliczek

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:

@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.

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:

"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."

The same applies to 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!