Java ternary (immediate if) evaluation

前端 未结 3 1459
南方客
南方客 2020-11-30 09:41

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

3条回答
  •  北海茫月
    2020-11-30 10:06

    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!

提交回复
热议问题