idea install jclasslib (omitted)
Implementation process
a++
code
public class CodeTest {
public static void main(String[] args) {
int a = 8;
a = a++;
// a = ++a;
System.out.println(a);
}
}
Open jclasslib to view the instructions.
Look at the bytecode part on the right,
0 bipush 8 --> push the value of 8 onto the stack, that is, push the value of 8 into the bottom of the operation stack;
2 istore_1 --> save the local variable a into the local Position 1 of the variable table, such as;
3 iload_1 --> pop 8 in the operation stack to a in the local variable table, at this time a is 8;
4 iinc 1 by 1 --> 8 in the local variable table Increment by 1, it becomes 9;
7 istore_1 --> the value in the operation stack, at this time 8 is still given to the 1st position of the local variable table, so 8 is given to a good position;
8 getstatic --> (virtual machine The call in is not important, no matter.)
11 iload_1 --> the 8 pop stack in the operation stack is given to a in the local variable table, so a is 8;
12 invokevirtual --> (call in the virtual machine, not important , Don't care.)
15 return -->Return.
So even though the ++ operation is done, the value in the stack is still 8, so 8 is returned;
++a
It can be seen that the difference with a++ is that iinc 1 by 1 is first followed by iload_1, so a is incremented first before being assigned to the local constant table.
So a++ is 8 and ++a is 9.