Java expressions are evaluated following the following rules:
In the following example:
int i = method1() + method2();
the order of evaluation is:
=
operator is evaluated to the address of i
.+
operator (method1()
) is evaluated.+
operator (method2()
) is evaluated.+
operation is evaluated.=
operation is evaluated, assigning the result of the addition to i
.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
.
In the following example:
int i = 1;
intArray[i] = ++i + 1;
the order of evaluation is:
=
operator is evaluated. This gives the address of intArray[1]
.1
to i
, and evaluates to 2
.+
is evaluated.+
operation is evaluated to: 2 + 1
-> 3
.=
operation is evaluated, assigning 3
to intArray[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: