Mihai Boisteanu wrote:. . . j = j + j++;
Now, the order is this one:
1) We sum up j + j, those in red.
2) Now the green stuff happen so j++ which means our j is now 11.
3) But, after this expression has been evaluated our j (blue) get the value of the evaluated expression which is the one in red that we calculated in the first step. So j = 20.
That value we had in red is practically stored until we finish evaluating our little expression.
No, that is incorrect. The ++ operator has a higher precedence than +, so it must be executed before the addition +. But an operator with a higher precedence has a narrower scope, so only the second
j is in the scope of the operator ++. The second
j is not in the scope of the + operator, but the expression
j++ is in its scope. Remember the value of
j++ is the same as the (old) value of
j.
What happens is this:
The value of j is put onto a stack.The value of j is put onto a stack.The value of j is incremented by 1, but this value is not put onto the stack.The two values on the stack are added.The stack looks like this:
That is how the old value of
j is used for
j++. You can work it out by creating a method
Now using the instruction
javap -c Foo, you get something like
iload_1
iload_1
iinc
iadd
as the interpretation of the bytecode. Notice there are numbers in the output, which show which
int is being incremented, and by how much, e.g. 1, 1, meaning the first
int incremented by 1.
If you use i += i++; instead, the bytecode looks exactly the same.
Putting the iload and stack together, we get
If you search this forum you will find many threads about this question; it seems to confuse everybody at some stage in their learning. If you try
i += ++i; it is much easier to understand, and in the bytecode the iinc comes before the second iload.