简体   繁体   English

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

[英]Java Compound Assignment Operator precedence in expressions

The output of the following code is declared as "6" when I try to execute this. 当我尝试执行此操作时,以下代码的输出被声明为“6”。

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. 当我试图通过这个时,表达式“k + = 3 + ++ k;应该被评估为k = k +(3 + ++ k);但在这种情况下输出应该是7.看起来就像它被评估为k = k + 3 + ++ k;这导致6。

Could someone please explain me why the expression was evaluated as "k + 3 + ++k" instead of " k + (3 + ++k); ? 有人可以解释一下为什么表达式被评估为“k + 3 + ++ k”而不是“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 . 看看JLS中的行为- 复合赋值运算符 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 . 然后,左手操作数的评估值(在您的情况下为1与右手操作数的结果相加,结果为5 Hence the result 6 . 因此结果6

Official Docs on Operators says 关于运营商的官方文件说

All binary operators except for the assignment operators are evaluated from left to right; 除了赋值运算符之外的所有二元运算符都是从左到右计算的; assignment operators are evaluated right to left. 赋值运算符从右到左进行计算。

So + is evaluated left-to-right ,where as assignment operators are evaluated right to left. 所以+ left-to-right进行评估,其中赋值运算符right to left.进行计算right to left.

Now you got your answer right ?? 现在你的答案正确吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM