I often happened to see discussions about this topic. Basically, here is the question. If you have such a code:
int a = 0; a = a++; System.out.println(a);
What does it print?
More than 50% of the programmers will answer 1, some of the remaining will say “I don’t know” and the others will say 0. Well “the others” are right!
Provided that such a code MUST NEVER BE WRITTEN, let’s try to understand, for academic purposes, why it prints 0.
The reason lies in the JLS (Java Language Specification). The JLS mandates that, in an assignment expression,
the right side of the = must be evaluated first and then the value of the expression must be assigned to the left side.
When the right side gets evaluated,
a++ evaluates to
0 since it is a post-increment. This value is then saved into
some temporary variable. At this point the post-increment takes place ->
a = a + 1 and, finally, the value of the
temporary variable is assigned to
a, losing the increment previously done!
If we translate that code in pseudo-code we have:
a = 0 temp = a (the value of the a++ expression) a = a + 1 (the effect of the post-increment) a = temp;
That’s why you get 0! I hope this is clear enough.
An important thing to say is that, if you use a good IDE you’ll get a warning about that assignment. For example,
using Eclipse (my version is 3.1.1 at the time or writing this post) I get: “The assignment to variable
a has no effect”.
Final Note: In C and C++ that expression gives an “undefined behaviour”! That means that there’s no specification about it.
Indeed, some compilers give 0 and others give 1 as the final value of