Java - parentheses and assignment

2019-05-28 22:17发布

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?

5条回答
Rolldiameter
2楼-- · 2019-05-28 22:54

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.

查看更多
Lonely孤独者°
3楼-- · 2019-05-28 23:04

Use this if you want 4

int r=1;
System.out.println((r=2) + r); // execute + is left-to-right
查看更多
Explosion°爆炸
4楼-- · 2019-05-28 23:08

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.

查看更多
【Aperson】
5楼-- · 2019-05-28 23:14

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.

查看更多
来,给爷笑一个
6楼-- · 2019-05-28 23:15

it's like this

(r + (r=2))
(1 + (r=2))
(1 + (2))
(3)
查看更多
登录 后发表回答