java运算符优先级与赋值

时间:2013-11-15 10:37:49

标签: java operators operator-precedence

如果有人能解释为什么会发生以下情况,我将不胜感激。非常感谢。

boolean b = true;
// Compiles OK.
// The LHS "assignment operand" requires no ()parentheses.
if (b=true || b==true);

// Reverse the ||'s operands, and now the code doesn't compile.
if (b==true || b=true);

// Add () around the RHS "assignment operand", and the code now compiles OK.
if (b==true || (b=true));

修改

顺便说一下,代码行#2的编译错误是:“意外类型”,并且发生在短路OR运算符所在的位置:

if (b==true || b=true);
//          ^ "unexpected type" compilation error occurs here.

编辑2 -

请注意,此问题中的代码片段是“高度人工的Java编码”的示例,因此在专业编写的代码中不会出现。

修改3 -

我是这个非常有用的网站的新手,我刚学会了如何制作和上传Java编译信息的截图。下图复制了我在上面第一个“编辑”中提供的信息。它显示了代码行#2的编译错误。

Code line #2 compilation error

3 个答案:

答案 0 :(得分:6)

赋值运算符=的优先级低于逻辑运算符||,因此您可以在赋值中使用逻辑运算符而无需额外的括号对。也就是说,你希望能够写

a = b || c;

而不是被迫写a = (b || c)

不幸的是,如果我们只使用运算符优先级,则此规则也适用于表达式的左侧。 a || b = c必须解析为

(a || b) = c;

即使你想要的是a || (b = c)

答案 1 :(得分:5)

分配在Java中具有最低优先级。因此,您的前两个表达式相当于:

if ( b = (true || b==true) );

if ( (b==true || b) = true );

第二个没有编译,因为表达式(b==true || b)不是lValue(可以分配给它的东西)。

如果添加括号,则在OR之前执行赋值,一切正常。

答案 2 :(得分:2)

使用运算符优先级(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)我们有这个(我添加了括号来表示优先级):

  1. if (b=(true || (b==true)))b将被分配到表达式并返回boolean,因此它适合条件;

  2. if (((b==true) || b)=true),左侧不适合赋值运算符(因为它是表达式而非变量);

  3. if (((b==true) || (b=true)))booleanboolean合并为ORbooleanboolean,因为b=变量和{{1}}返回指定的值。

相关问题