java for this.x=x,怎么是x = 20; x = ++ x + ++ x + x ++; java中x的最终值是65

how is this possible as post increment operator should increase x to 66?

When i did the same for y= ++x + ++x + x++; it gave a value 65 for y and 23 for x.

So let me know how is java compilers solving these expression.

解决方案

Let Java show you. javap -c MyClass shows you bytecode:

public static void main(java.lang.String[]);

Code:

0: bipush 20

2: istore_1

3: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;

6: iinc 1, 1

9: iload_1

10: iinc 1, 1

13: iload_1

14: iadd

15: iload_1

16: iinc 1, 1

19: iadd

20: dup

21: istore_1

22: invokevirtual #3 // Method java/io/PrintStream.println:(I)V

25: return

And the result is completely logical if you think about it: you have two preincrements and one postincrement. So, your code is in effect:

y = 0

x++ // 21

y += x

x++ // 22

y += x

y += x // (still 22!)

x++ // 23

x = y // (21 + 22 + 22 at this point)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值