表达式中Java复合赋值运算符优先级 [英] Java Compound Assignment Operator precedence in expressions

查看:181
本文介绍了表达式中Java复合赋值运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试执行此操作时,以下代码的输出被声明为6。



当我想到这一点时,表达式k + = 3 + ++ k;应该被评估为k = k +(3 + ++ k);但在这种情况下,输出应为7.看起来被评估为k = k + 3 + ++ k;这导致了6。



有人可以解释一下为什么表达式被评估为k + 3 + ++ k而不是k +(3 + ++ K); ?

  public class TestClass {

public static int m1(int i){
返回++我;
}

public static void main(String [] args){

int k = m1(args.length);
k + = 3 + ++ k;
System.out.println(k);
}

}

解决方案

看看 JLS - 复合分配运算符 。我将在这里引用相关的两段,只是为了答案的完整性:


否则,左侧操作数被保存,然后评估右侧操作数。如果此评估突然完成,那么赋值表达式会因为相同的原因而突然完成,并且不会发生分配。



否则,左侧变量的保存值右侧操作数的值用于执行复合赋值运算符指示的二进制运算。如果这个操作突然完成,那么赋值表达式由于相同的原因而突然完成,并且没有分配。


重点是我的。 >

所以,左手操作数先被评估,只做一次。然后,在您的情况下,左手操作数的评估值 1 添加了右手操作数的结果,结果是 5 。因此,结果 6


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.

这篇关于表达式中Java复合赋值运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆