Java increment and assignment operator [duplicate]

No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x and post-increment x++ compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.

Here is the sequence of events that leads to what you see:

  • x is assigned 10
  • Because of ++ in post-increment position, the current value of x (i.e. 10) is stored for later use
  • New value of 11 is stored into x
  • The temporary value of 10 is stored back into x, writing right over 11 that has been stored there.

Leave a Comment