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

后端 未结 10 1232
温柔的废话
温柔的废话 2021-01-04 10:16

Consider this function:

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

Is it required

10条回答
  •  不知归路
    2021-01-04 10:41

    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).

提交回复
热议问题