Java ternary (immediate if) evaluation

Mike Pone picture Mike Pone · Jun 10, 2009 · Viewed 23.2k times · Source

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;

Answer

Michael Myers picture Michael Myers · Jun 10, 2009

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.