Scenario 1 (a finally equals 5)
a=5;
a=a++;
IS NOT THE SAME THING AS
Scenario 2 (a finally equals 6)
a=5;
int a
To understand this you must break down what is happening in Scenario 2.
- Create a new primitive int equal to 5 and place a reference to it inside
a.
- Create a new primitive int equal to the value
a is referring to
plus 1.
- Store the reference to that new primitive int inside
a.
Scenario 1 is totally different.
- Create a new primitive int equal to 5 and place a reference to it inside
a.
- Create a new primitive int equal to the value a is referring to.
- Add 1 to the original primitive int which has probably already been handed off to the garbage collector.
The reason you are confused is because you think a is always referring to the same place in memory. As soon as you said a=a you changed locations in memory. This is now a NEW a, not the same old a, so essentially your ++ is doing nothing in this case.
a=a++; doesn't mean let a stay as a and then after this statement add 1. What it actually means is make a equal to a NEW int that just so happens to have the same value as a and then add 1 to that old int I just threw into the black hole.
Edit: response to comments
If you do not want to lose your original a variable you will have to write your code differently.
int a = 5;
int b = a; //stores the original value
a++; //now a equals 6