Java - parentheses and assignment

拟墨画扇 提交于 2019-12-06 08:59:02

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.

Use this if you want 4

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

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.

it's like this

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

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.

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