i++ 和 ++i 的差别
单独使用的时候是没有区别的,但是如果当成运算符,就会有区别了!
如图所示,我们用a=i++和a=++i举例说明
1.先说a=i++,这个运算的意思是先把i的值赋予a,然后在执行i=i+1;
当i初始等于3时,执行a=i++,最终结果a=3,i=4.
2.而a=++i,这个的意思是先执行i=i+1,然后在把i的值赋予a;
当i初始等于3时,执行a=++i,最终结果a=4,i=4.
实际的区别在于字节码中 load 和 iinc 执行的顺序不同
先看一段代码
public static void main(String[] args) {
int i = 10;
int a = 0;
int b = 0;
a = i++;
b = ++i;
System.out.println("i= "+i+" a= "+a+" b= "+b);
}
结果为
i= 12 a= 10 b= 12
查看字节码文件
0 bipush 10
2 istore_1
3 iconst_0
4 istore_2
5 iconst_0
6 istore_3
7 iload_1
8 iinc 1 by 1
11 istore_2
12 iinc 1 by 1
15 iload_1
16 istore_3
17 return
字节码解析
bipush 10
将 10加载到操作数栈中
istore_1
将操作数栈栈顶元素弹出,放入局部变量表的slot 1中
iconst_0
istore_2
a=0,所以用iconst_0表示0
iconst_0
istore_3
iload_1
将槽位1上的值加载到操作数栈中
iinc 1 by 1
将局部变量表槽位1上的值加一
istore_2
将操作数栈栈顶元素弹出,放入局部变量表的slot 2中
iinc 1 by 1
将局部变量表槽位1上的值加一
iload_1
istore_3
最后的值为 i = 12, a = 10, b = 12
再看一题
public static void main(String[] args) {
int i = 0;
int x = 0;
while (x < 10){
i = i++;
x++;
}
System.out.println(i);
}
结果为
0
查看字节码文件
0 iconst_0
1 istore_1
2 iconst_0
3 istore_2
4 iload_2
5 bipush 10
7 if_icmpge 21 (+14)
10 iload_1
11 iinc 1 by 1
14 istore_1
15 iinc 2 by 1
18 goto 4 (-14)
21 getstatic #2 <java/lang/System.out : Ljava/io/PrintStream;>
24 iload_1
25 invokevirtual #3 <java/io/PrintStream.println : (I)V>
28 return
第十行 iload_1
第十一行 iinc 1 by 1
第十二行 istore_1
一次循环之后i的值被覆盖为0,所以最终结果为0