I’ve often seen discussions about this topic. Basically, here is the question. If you have code like this:
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 rest will say “I don’t know” and the others will say 0. Well, “the others” are right!
Keeping in mind that code like this 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 earlier increment!
If we translate that code into pseudocode 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.
One important point 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 of writing this post) I get: “The assignment to variable a has no effect”.
Final Note: In C and C++ that expression has “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 a.