带赋值的Java运算符优先级

用户名

如果有人可以解释以下原因,我将不胜感激。非常感谢。

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的编译错误。

代码行2编译错误

若昂·门德斯

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

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

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

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

如果添加括号,则在“或”之前进行赋值,一切正常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章