Java Compound Assignment Operator precedence in expressions

守給你的承諾、 提交于 2019-12-11 04:56:43

问题


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);
}

}


回答1:


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.




回答2:


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.

Now you got your answer right ??



来源:https://stackoverflow.com/questions/18036584/java-compound-assignment-operator-precedence-in-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!