From page 280 of OCP Java SE 6 Programmer Practice Exams, question 9:
int x = 3;
x = x++;
// x is still 3
In the explanation we can read that:
The
x = x++;
line doesn't leavex == 4
because the++
is applied after the assignment has occurred.
I agree that x
is 3, I understand post-incremenation.
I don't agree with the explanation. I would replace "after" with "before".
I thought it works like this:
x
is 3.x++
is executed. I see this post-increment operator as a function:int operator++() { int temp = getX(); setX(temp + 1); return temp; }
So, after
x++
execution,x
is 4, but the value returned fromx++
expression is3
.- Now, the assignment
=
. Simply write returned3
tox
.
So, in my eyes ++
is applied before the assignment has occurred. Am I wrong?
Okay, hold on. This is actually confusing and perhaps suggests an incorrect behavior.
You have the expression†:
What happens is (JLS 15.26.1):
x
is evaluated (to produce a variable).( x++ )
is evaluated (to produce a value).x
is post-incremented, and the result of the expression is the old value ofx
.x
, is assigned the value produced by the evaluation of the right-hand side, which is the old value ofx
.So the post-increment happens before the assignment.
(Therefore, as we know, the value of
x
after executing the statementx = x++;
is the same as the value ofx
before executing the statement, which is3
.)You are right.
Technically, the way it is specified is that
x++
is evaluated before its result is stored and during the evaluation of the assignment operator. Sox++
can be interpreted as happening either before or during the assignment. Not after, so the book appears to be wrong either way.Just for the heck of it, we may also look at some bytecode:
The
iinc
happens before theistore
.†: The parentheses have no effect on the evaluation, they are just there for clarity.