Is the left-to-right order of operations guaranteed in Java?

Pacerier picture Pacerier · Jan 31, 2012 · Viewed 7.5k times · Source

Consider this function:

public static final int F(int a, int b) {
    a = a - 1 + b;
    // and some stuff
    return a;
}

Is it required for implementations of JVMs to execute - 1 before + b?

If we have a system profiler attached to the JVM, will we see the + b operation being carried out before the + 1 operation?

Answer

Óscar López picture Óscar López · Jan 31, 2012

Yes, it's in the Java language specification, §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 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.