views:

1816

answers:

5

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;
+7  A: 

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

Integer test = null;
if ( test != null ) { 
    test = test.intValue();
}
else {
    test = 0;
}
stevedbrown
A: 

This don't throw NPE

Daniel Moura
Is my answer wrong? Why down vote?
Daniel Moura
It's not wrong, it's just not very clear, has horrible grammar and "is not helpful".
Mike Pone
+13  A: 

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.

Michael Myers
Bingo! Thanks.
Mike Pone
Sometimes it pays to have the JLS always open. The rest of the time, I guess I'm just crazy. Or extremely geeky. Yeah, I'll go with that one.
Michael Myers
+1  A: 

BTW, this is not called a "short circuit statement" - it's the "ternary" or (most correctly) "conditional operator". The short circuit boolean operators are || and &&.

Michael Borgwardt
Shhh! Don't say "ternary" out loud! Jon Skeet might hear you!
Michael Myers
updated the question per your suggestion.
Mike Pone
@mmyers: What's wrong with trenary?
Tim Büthe
A: 

the syntax is wrong .

Integer test = (test != null) ? test.intValue() : 0;

hope it helps ....

Idan