Java ternary (immediate if) evaluation
Asked Answered
H

3

35

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;
Hainan answered 10/6, 2009 at 21:47 Comment(2)
It's also something simple enough that you could just try it out and see what happens :)Antakiya
Which gives you information on one particular instance. Better to find what the standard says.Hagberry
J
63

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.

Jolinejoliotcurie answered 10/6, 2009 at 21:55 Comment(0)
E
24

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!

Epp answered 26/2, 2013 at 6:44 Comment(1)
Interesting point, thanks Michal. Because A.intValue() is of type int, the reference to B must be auto unboxed. But it's null, so it throws NPE. In Java 8/Eclipse Luna with null analysis turned on, this test doesn't even compile!Spermiogenesis
K
8

No, it couldn't. That's the same as:

Integer test = null;
if ( test != null ) { 
    test = test.intValue();
}
else {
    test = 0;
}
Kitchenmaid answered 10/6, 2009 at 21:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.