当 Java if 语句 同时具有赋值和相等检查 OR
-d 时,它是如何工作的?
public static void test() {
boolean test1 = true;
if (test1 = false || test1 == false) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
为什么这个打印是 FALSE?
test1=false
,test1==false
是 false
,false || false
是 false or false
,即 false
。
test1 = true
表达式没有按照您的想法进行解析。它不是
(test1=false) || (test1 == false)
在这种情况下,结果应该是 true
,但是
test1 = (false || test1 == false)
首先计算 false || test1 == false
表达式的值,它是 false
,因为 test1
设置为 true
进入计算。
之所以这样解析,是因为||
的precedence低于==
运算符,但高于赋值运算符=
的优先级。
基本上,这是一个优先问题。您假设您的代码等效于:
if ((test1 = false) || (test1 == false))
……但事实并非如此。它实际上相当于:
if (test1 = (false || test1 == false))
...相当于:
if (test1 = (false || false))
(因为 test1
是 true
开头)
...相当于:
if (test1 = false)
它将值 false
分配给 test1
,表达式的结果是 false
。
有关运算符优先级的有用表,请参阅 Java tutorial on operators。
https://i.stack.imgur.com/UcG6x.gif
表达式 test1 = false || test1 == false
将在以下步骤中进行评估。
STEP:1- test1 = false || test1 == false
//==
的优先级最高
STEP:2- test1 = false || false
// 运算符 ||
具有更高的优先级
步骤:3- test1 = false
步骤:4- false
由于表达式的布尔值变为 false。因此正在执行 else 语句。
(test1 = false || test1 == false)
返回 false,因为它们都是 false。(test1 = false || test1 == true)
这是 true,因为其中一个是 true
不定期副业成功案例分享
((test1 = false) || test1 == false)
,总价值将是true
。==
高于||
,但=
低于||
。||
)的优先级较低的规则就足够了。||
和==
的相对优先级仅与显示解析 not 与test1 = ((false || test1) == false)
中的情况相关,我认为任何人都不会合理地期望(顺便说一下,相对优先级) ,或者更一般地说,||
、&&
的优先级低于关系,也很容易记住,因为一直使用)。||
和==
与||
和=
的相对优先级解释了为什么这与a == b || c == d
的(常见)情况不同。