java 变量值,Java值加变量++

Consider the following code

int val1 = 3;

val1++;

int val2 = val1++;

System.out.println(val1);

System.out.println(val2);

Val1 value = 5;

Val2 value = 4;

Why is the value of Val1 "5"?

As I understand it it should be 4, because:

at line1 it is assigned value of 3, on line2 1 gets added by way of val1++ which result in val1 being 4.

Val2 is the value of val1 thus 4, plus 1 which is 5

HOwever the compiler gives val1 a value of 5 and val2 a value of 4, what am I not understanding or missing here?

I realize val1++ is used a second time but it is assigned to val2, and should not effect val1s value, or am I wrong?

解决方案

a++ is known as postfix.

add 1 to a, returns the old value.

++a is known as prefix.

add 1 to a, returns the new value.

so int val2 = val1++; will return the old Value (4)

and still add one to val1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值