Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 603
Pacerier Avatar asked Jan 31 '12 14:01

Pacerier


People also ask

Does Java obey order of operations?

Yes, Java follows the standard arithmetic order of operations.

Does Java do math from left to right?

Java enforces left-to-right for operators with the same precedence.

Is left-associative in Java?

Operators in Java can be left-associative, right-associative, or have no associativity at all. Left-associative operators are assessed from left to right, right-associative operators are reviewed from right to left, and operators with no associativity are evaluated in any order.


2 Answers

Actually, I will disagree with the rest of the answers. The JLS §15.7 that people are referring to discusses the evaluation of operands. That is, in the expression

x = foo() - 1 + bar()

, in which order will the methods be invoked.

The relevant section is §15.7.3, which specifies

An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects [...]

Since the expression x = x - 1 + q is equivalent in all ways to x = x + q - 1, a conforming implementation is allowed to rewrite the expression (if it for some reason should decide that is more efficient).

like image 89
Rasmus Faber Avatar answered Oct 21 '22 03:10

Rasmus Faber


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.

like image 30
Óscar López Avatar answered Oct 21 '22 02:10

Óscar López