java复合运算符,表达式中Java复合赋值运算符优先级

The output of the following code is declared as "6" when I try to execute this.

When I am trying to think through this, the expression "k += 3 + ++k; should have been evaluated as k = k + (3 + ++k); but in this case the output should have been 7. Looks like it was evaluated as k = k + 3 + ++k; which resulted in 6.

Could someone please explain me why the expression was evaluated as "k + 3 + ++k" instead of " k + (3 + ++k); ?

public class TestClass {

public static int m1(int i){

return ++i;

}

public static void main(String[] args) {

int k = m1(args.length);

k += 3 + ++k;

System.out.println(k);

}

}

解决方案

Take a look at the behaviour in JLS - Compound Assignment Operator. I'll quote the relevant two paragraphs here, just for the sake of completeness of the answer:

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Emphasis mine.

So, the left hand operand is evaluated first, and it is done only once. And then, the evaluated value of left hand operand, 1 in your case, is added with the result of right hand operand, which turns out to be 5. Hence the result 6.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值