简体   繁体   English

Java - 括号和赋值

[英]Java - parentheses and assignment

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? 输出是:3。但我预计4因为我认为括号内的代码是先执行的?

Use this if you want 4 如果你想要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 . +是从左到右,表达式(r=2)2

Refer JLS 15.7 参考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. 如果运算符是复合赋值运算符(第15.26.2节),则对左侧操作数的计算包括记住左侧操作数表示的变量并获取并保存该变量的值以用于隐含的二进制操作。

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. 如果对二元运算符的左侧操作数的求值突然完成,则右侧操作数的任何部分似乎都没有被评估。

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.

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. 语句r=2值为2.括号之间的嵌套表达式首先被处理。

For instance: 例如:

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

Output: 输出:

6

Why? 为什么? Because r = 2 + 1 returns 3 . 因为r = 2 + 1返回3

Same as: 如同:

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

Output still 6 because (2 + 1) is evaluated before multiplication. 输出仍为6因为在乘法之前评估(2 + 1)

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

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