Search code examples
javaconditional-operatorshort-circuiting

Java ternary (immediate if) evaluation


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;

Solution

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