Let's start with the basics of increment work.
Take an example:
int x = 1; int y = x++; System.out.println(y +""+x);
Output: 12
In the first approximation it may seem that the following occurred in the second line:
- At first, the current value was assigned, the unit was written to the variable y .
- Then the variable x is increased by one.
However, a closer look, says that everything was much more complicated. To do this, you need to look at the decompiled byte-code of the same example:
byte x = 1; //int x = 1 - ориг. код byte var10000 = x; //2 строка ориг. кода int x1 = x + 1; //2 строка ориг. кода byte y = var10000; //2 строка ориг. кода System.out.println(y + "" + x1);
From it, you can easily see that the equivalent of the "simple" line is int y = x++; become three lines at once. It looks like they work as follows:
- First, the variable var10000 is allocated to which x is written;
- After the creation of the variable x1 in which the value increases by one.
Next, the variable y is assigned the value var10000 - that is, the old value x .
It turns out that the prefix increment contains the creation of two new variables.
From the above, it is obvious that the original expression:
int i = 1; i=i++; System.out.println(i);
in the decompiled byte code will look like:
byte i = 1; //x заменили на i byte var10000 = i; int i1 = i + 1; i = var10000; //Мы по сути y заменили i System.out.println(i);
That is, the last operation before outputting to the console is an entry in the variable i of a temporary value. In accordance with the priority of operations , assignment is always performed after the increment / decrement.
Ps . Additionally, a similar question was given 17! Answers in English stackflow .