Java - parentheses and assignment

余生颓废 提交于 2019-12-22 20:45:33

问题


The code:

int r=1;
System.out.println(r + (r=2));

The output is: 3. But I expected 4 because I thought the code inside the parentheses is executed first?


回答1:


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.




回答2:


Use this if you want 4

int r=1;
System.out.println((r=2) + r); // execute + is left-to-right



回答3:


Associativity of + is left-to-right , and the value of the expression (r=2) is 2.

Refer JLS 15.7

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.

If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.




回答4:


it's like this

(r + (r=2))
(1 + (r=2))
(1 + (2))
(3)



回答5:


The value of statement r=2 is 2. Nested expressions between brackets are processed first though.

For instance:

int r=2;
System.out.println(r * (r=2 + 1));

Output:

6

Why? Because r = 2 + 1 returns 3.

Same as:

int r=2;
System.out.println(r * (2 + 1));

Output still 6 because (2 + 1) is evaluated before multiplication.



来源:https://stackoverflow.com/questions/17808093/java-parentheses-and-assignment

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