Expression evaluation order
suggest changeJava expressions are evaluated following the following rules:
- Operands are evaluated from left to right.
- The operands of an operator are evaluated before the operator.
- Operators are evaluated according to operator precedence
- Argument lists are evaluated from left to right.
Simple Example
In the following example:
int i = method1() + method2();
the order of evaluation is:
- The left operand of
=operator is evaluated to the address ofi. - The left operand of the
\+operator (method1()) is evaluated. - The right operand of the
\+operator (method2()) is evaluated. - The
\+operation is evaluated. - The
=operation is evaluated, assigning the result of the addition toi.
Note that if the effects of the calls are observable, you will be able to observe that the call to method1 occurs before the call to method2.
Example with an operator which has a side-effect
In the following example:
int i = 1;
intArray[i] = ++i + 1;
the order of evaluation is:
- The left operand of
=operator is evaluated. This gives the address ofintArray[1]. - The pre-increment is evaluated. This adds
1toi, and evaluates to2. - The right hand operand of the
\+is evaluated. - The
\+operation is evaluated to:2 + 1->3. - The
=operation is evaluated, assigning3tointArray[1].
Note that since the left-hand operand of the = is evaluated first, it is not influenced by the side-effect of the ++i subexpression.
Reference:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents