Possible Duplicate:
Decrement in java
I was looking at this question, Decrement in Java and it piqued my curiosity. I understand how post/pre increment/decrement work, but I want to know why it works the way it does in that particular situation.
For example,
int x = 5;
x--;
Will very obviously set x to be 4. But if you do,
x = x--;
x will be 5 still (as discovered by the poster of the referenced question). From my understanding of post decrement, it returns the value before it modifies it. So what I expect to happen would be that x = 5
happens first. (keeping consistent with the above). Then, x is decremented, so in my mind, x--;
would run, which in the above clearly sets x to be 4.
I mean, yes, it's easy enough just to do x--;
but I would like to understand why Java's post decrement works this way.
I tried the code below and it worked exactly as expected.
int x = 5;
int y = x--;
y
was set to 5 and x
was properly decremented. Why doesn't the same happen for x = x--;
?