Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 601
Mike Pone Avatar asked Jun 10 '09 21:06

Mike Pone


People also ask

Is ternary faster than if?

Yes! The second is vastly more readable.

Can we use ternary operator in if condition in Java?

Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.

Is Java ternary operator lazy?

It's worth mentioning that the operator is lazy in the sense that only the used expression is evaluated: The ternary operator will not evaluate the unused branch.

Is ternary better than if else?

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).


2 Answers

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.

like image 188
Michael Myers Avatar answered Oct 05 '22 01:10

Michael Myers


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!

like image 31
Michał Króliczek Avatar answered Oct 05 '22 03:10

Michał Króliczek