Jave evaluates expressions from left to right while respecting operator precedence. The first expression encountered is the compound assignment operator, *=. Since E1 op= E2 is the same as E1 = (T)((E1) op (E2)) we can expand the original expression as follows.
i = (int)((i) * (2*i + i++));
Now the first operator encountered on the left is the simple assignment operator, =. The left operand is the variable i and the right operand is the entire expression ((i) + (2*i + i++)), because the simple assignment operator has lower precedence that all of the operators that follow it on the right.
Java will first evaluate the left hand operand of the first multiplication operator, so we can write the value 1 in place of i.
i = (int)((1) * (2*i + i++));
Java will see that the right hand operand of the first multiplication operator is the expression, (2*i + i++), so Java will evaluate the entire right hand operand. The evaluation of the right hand operand begins by evaluating the expresion 2*i. The result is as follows.
(2 + i++)
The next operand is the addition operator. The left operand is the value 2 and the right operand is the postfix expression i++. Both the left and the right operands are evaluated before the addition operation is complete.
(2 + 1)
At this point, the value of i is 2; because i was incremented by the postfix expression.
The result of the above expression is 3, so our original statement can be simplified as follows.
i = (int)((1) * (3)); // At this point, i = 2.
The above can be simplified as follows.
i = (int)(3);
Prior to the evaluation of the simple assignment expression, the value of i is 2. After the evaluation of the assignment expression the value of i will be 3 and the old value will be lost.
Please note that the above process demonstrates what Java does, but it is not the simplest way for people to evaluate expressions. For us, it is a little easier to first go through the entire expression and evaluate the postfix and prefix expression first. On a second pass through the expression from left to right we can then work through the other operators. I didn't demonstrate that approach above, because I wanted to demonstrate when the postfix expression really does increment the value of i.
Please also note that the real exam does not focus on operator precedence. The real exam assumes that programmers use parenthesis to control the order of evaluation.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>