Originally posted by Jane Griscti:
If you re-write the code as follows:
You'll see an output of:
'a' IS assigned a value of '11' after the postfix, but since the expression result is also assigned to 'a' in the original version, the postfix result is overwritten.
Java does something like this:
- Evaluate 'a', which is 10.
- Postfix operator has highest precedence. Take the initial value of 'a', 10, and keep it in memory for use in the '+' expression. Increment 'a' by '1'; so 'a' = 11.
- Now do the '+', initial value of 'a' + initial value of 'a' = 10 + 10 = 20
- The right hand side of the expression completes, with a value of '20'.
- Assign the result, 20, to 'a' which OVERWRITES the old value of 11.
Hope that helps.
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment
expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the
value 1 is added to the value of the variable and the sum is stored back into the variable. Before the
addition, binary numeric promotion (�5.6.2) is performed on the value 1 and the value of the variable.
If necessary, the sum is narrowed by a narrowing primitive conversion (�5.1.3) to the type of the
variable before it is stored. The value of the postfix increment expression is the value of the variable
before the new value is stored.