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?
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...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With