don't use ++ and = on the same variable in the same expression, the increment will not take into effect. from Java™ Puzzlers: Traps, Pitfalls, and Corner Cases By Joshua Bloch, Neal Gafter
Puzzle #25:
As the puzzle's title suggests, the problem lies in the statement that does the increment:
j = j++;
Presumably, the author of the statement meant for it to add 1 to the
value of j, which is what the expression j++ does. Unfortunately, the
author inadvertently assigned the value of this expression back to j.
When placed after a variable, the ++ operator functions as the postfix
increment operator [JLS 15.14.2]: The value of the expression j++ is
the original value of j before it was incremented. Therefore, the
preceding assignment first saves the value of j, then sets j to its
value plus 1, and, finally, resets j back to its original value. In
other words, the assignment is equivalent to this sequence of
statements:
int tmp = j;
j = j + 1;
j = tmp;
as a result your doe looks like this when it evaluates:
int x=20
int sum;
x=x+1; //x=20=1
sum=x; //sum and x equal 21
x=x+1; //x=22
sum=sum+x; //sum=43
sum= sum+x; //sum=65
x= x+1; //x=23
x=sum; //x=65;
This is why x=65 and not 66