java运算符优先级与赋值

use*_*290 8 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));
Run Code Online (Sandbox Code Playgroud)

编辑 -

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

if (b==true || b=true);
//          ^ "unexpected type" compilation error occurs here.
Run Code Online (Sandbox Code Playgroud)

编辑2 -

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

编辑3 -

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

代码行#2编译错误

Jon*_*oni 6

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

a = b || c;
Run Code Online (Sandbox Code Playgroud)

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

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

(a || b) = c;
Run Code Online (Sandbox Code Playgroud)

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


Joã*_*des 5

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

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

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

(b==true || b)

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

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

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

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