AvrDragon
AvrDragon

Reputation: 7479

Are short-circuits operators allways executed left to right?

So if code:

if(f() && false) {
    // never happens
}

Can i be always sure that f() will be called and will be never 'optimised-away' by compiler?

Upvotes: 4

Views: 405

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533720

The javac compiler does very little optimisation.

The JIT can optimise code away but in this case you can be sure that && and || are always evaluated left to right.

All binary operators except for the assignment operators are evaluated from left to right

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html


From the JLS.

15.7. Evaluation Order

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 is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html

Upvotes: 7

Related Questions