The precedence and associativity rules specify the order of the operators but not the order in which the operands of a binary operator are evaluated. Operands are evaluated strictly from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. This rule takes precedence over any other rules that govern expressions. Consider this expression:
a + b * (c + 10 * d) / e
a , b , c , d , and e are evaluated in this order. If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code because a is evaluated to 0 before ++a is evaluated to 1 .
int a = ; int x = a + (++a);
But x becomes 2 in the following code because ++a is evaluated to 1 , and then a is evaluated to 1 .
int a = ; int x = ++a + a;
The order for evaluating operands takes precedence over the operator precedence rule. In the former case, (++a) has higher precedence than addition ( + ), but since a is a left-hand operand of the addition ( + ), it is evaluated before any part of its right-hand operand (e.g., ++a in this case).
In summary, the rule of evaluating an expression is:
Rule 1: Evaluate whatever subexpressions you can possibly evaluate from left to right.
Rule 2: The operators are applied according to their precedence, as shown in Table 3.10.
Rule 3: The associativity rule applies for two operators next to each other with the same precedence.
Applying the rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows :
The result happens to be the same as applying Rule 2 and Rule 3 without applying Rule 1. In fact, Rule 1 is not necessary if no operands have side effects that change the value of a variable in an expression.