java 累加赋值,Java增量和赋值运算符

I am confused about the post ++ and pre ++ operator , for example in the following code

int x = 10;

x = x++;

sysout(x);

will print 10 ?

It prints 10,but I expected it should print 11

but when I do

x = ++x; instead of x = x++;

it will print eleven as I expected , so why does x = x++; doesn't change the the value of x ?

解决方案

No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x and post-increment x++ compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.

Here is the sequence of events that leads to what you see:

x is assigned 10

Because of ++ in post-increment position, the current value of x (i.e. 10) is stored for later use

New value of 11 is stored into x

The temporary value of 10 is stored back into x, writing right over 11 that has been stored there.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值