i++与 ++i

1 篇文章 0 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值