1.第一种
public class TestStack {
public static void main(String[] args) {
int i = 8;
i = i++;
System.out.println(i);
}
}
8
Process finished with exit code 0
Bytecode
0 bipush 8 //将8压入fram(栈帧)里面的operand stack中
2 istore_1 //将前面压栈的值8取出来给下标为1的变量也就是程序里的i
3 iload_1 //重新压入到operand stack中
4 iinc 1 by 1 // 加1
7 istore_1 //将前面压栈的值8取出来给下标为1的变量也就是程序里的i
8 getstatic #2 <java/lang/System.out>
11 iload_1
12 invokevirtual #3 <java/io/PrintStream.println>
15 return
因此还是8
2.第二种
public class TestStack {
public static void main(String[] args) {
int i = 8;
i = ++i;
System.out.println(i);
}
}
9
Process finished with exit code 0
Bytecode
0 bipush 8
2 istore_1
3 iinc 1 by 1
6 iload_1
7 istore_1
8 getstatic #2 <java/lang/System.out>
11 iload_1
12 invokevirtual #3 <java/io/PrintStream.println>
15 return
这种因为是先加1后再次压入operand stack中,而后再次用istore_1赋值给下标1的变量i,所以后面取到的都是9
3.第三种
public class TestStack {
public static void main(String[] args) {
int i = 8;
++i;
System.out.println(i);
}
}
或者
public class TestStack {
public static void main(String[] args) {
int i = 8;
i++;
System.out.println(i);
}
}
产生的结果及指令一样
9
Process finished with exit code 0
Bytecode
0 bipush 8
2 istore_1
3 iinc 1 by 1
6 getstatic #2 <java/lang/System.out>
9 iload_1
10 invokevirtual #3 <java/io/PrintStream.println>
13 return