Expression evaluation order

suggest change

Java expressions are evaluated following the following rules:

Simple Example

In the following example:

int i = method1() + method2();

the order of evaluation is:

  1. The left operand of = operator is evaluated to the address of i.
  2. The left operand of the \+ operator (method1()) is evaluated.
  3. The right operand of the \+ operator (method2()) is evaluated.
  4. The \+ operation is evaluated.
  5. The = 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.

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:

  1. The left operand of = operator is evaluated. This gives the address of intArray[1].
  2. The pre-increment is evaluated. This adds 1 to i, and evaluates to 2.
  3. The right hand operand of the \+ is evaluated.
  4. The \+ operation is evaluated to: 2 + 1 -> 3.
  5. The = 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:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Expressions:
* Expression evaluation order

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
140 Expressions
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap