J2EEOnline J2EEOnline

Classes/Objects  «Prev  Next»
Lesson 8 Determining order of evaluation
ObjectiveDescribe how operator precedence and associativity is used.

Order of evaluation

Describe how operator precedence and associativity is used to determine the order in which expressions are evaluated.
The order of evaluation of Java expressions is dependent on the precedence and associativity of the operators used in the expression, and the use of parentheses. In general, the operands of expressions are evaluated in a left-to-right order before any operations are performed. The exceptions to this are expressions involving the &&, ||, and ternary operators.
Once an expression's operands are evaluated, the operators are applied according to operator precedence and associativity. The assignment operator is the only right-associative binary operator. Parentheses can be used to change the ordering imposed by precedence and associativity.
The following table shows the precedence of Java's operators. Higher-level operators take precedence over lower-level operators.
Operators at the same level are evaluated based on the order they appear and their associativity.
  1. Order of evaluation: The order in which expressions are evaluated.
  2. Precedence: The order in which operations are performed.

Operator precedence table

Java already has a rule in place for just such a situation. Table 4.8 lists the precedence of operators: the operator on top has the highest precedence, and operators within the same group have the same precedence and are evaluated from left to right.
Table 4.8 Precedence of operators

Let us execute an expression that uses multiple operators (with different precedence) in an expression:
int int1 = 10, int2 = 20, int3 = 30;
System.out.println(int1 % int2 * int3 + int1 / int2);

Prints 300
Because this expression defines multiple operators with different precedence, it is evaluated as follows:
(((int1 % int2) * int3)) + (int1 / int2)
(((10 % 20) * 30)) + (10 / 20)
( (10 * 30)) + (0)
( 300 )
Java Operator Precedence
The Precedence program provides an example of how complex expressions are evaluated.