What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to
According to Byte code obtained from the class files,
Both assignments increment x, but difference is the timing of when the value is pushed onto the stack
In Case1
, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)
In Case2
, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)
Case 1:
int x=7;
x=x++;
Byte Code:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
Case 2:
int x=7;
x=++x;
Byte Code
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8