Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does all evaluation happen from left to right?

Tags:

java

String foo = null;

if(foo == null || foo.equals("")){
    //this is only safe if I'm guaranteed that the evaluation happens from left to right
}

In Java, is there such a guarantee? Or do I need to perform these tests in tandem to be sure?

like image 736
Yevgeny Simkin Avatar asked Oct 25 '25 07:10

Yevgeny Simkin


2 Answers

Yes. From JLS section 15.24:

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

The fact that the right-hand operand won't even be evaluated unless the left-hand operand is true means it has to be evaluated left-to-right... but in fact, that's the case for all operators. From JLS 15.7:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

It's also true for method (and constructor) arguments. For example, from section 15.12.4.2 (Evaluate Arguments, part of Run-Time Evaluation of Method Invocation):

The argument expressions, if any, are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason.

(It's interesting to note the "appears to" here - it's okay for the JVM to actually evaluate them out-of-order, so long as that's not observable...)

like image 160
Jon Skeet Avatar answered Oct 27 '25 20:10

Jon Skeet


The order is from left to right for ||, '&&'.

For || operator. If it sees if a||b, if a is false, it will check for b.

like image 34
pinkpanther Avatar answered Oct 27 '25 20:10

pinkpanther