[英]Java: OR Operator after AND in “If” Statement
Based on this and this answer Java employs short circuiting with regard to &&
and ||
基于此和此答案,Java对
&&
和||
采用短路 operators. 操作员。 It also gives
&&
higher precedence over ||
这也给
&&
了更高的优先级||
. 。 Yet the following code evaluates to
true
: 但是,以下代码评估为
true
:
boolean condition1 = true;
boolean condition2 = true;
boolean condition3 = true;
if ( !condition3 && condition1 || condition2 ) {
System.out.println("Condition is true"); // prints Condition is true
}
Since condition3
is set to true
this should cause !condition3
to be false so why is Java even checking condition1
? 由于
condition3
设置为true
这应该导致!condition3
为false,那么Java为什么还要检查condition1
呢?
If I add parentheses around the first condition it still evaluates to true: 如果我在第一个条件周围加上括号,它仍会评估为true:
if ( (!condition3) && condition1 || condition2 ) {
System.out.println("Condition is true");
}
I understand why this code evaluates to true: 我了解为什么这段代码评估为true:
if ( condition1 || condition2 && !condition3) {
System.out.println("Condition is true");
}
Because once Java encounters the ||
因为一旦Java遇到
||
after condition1
it doesn't even bother checking the following conditions. 在
condition1
之后,它甚至不必检查以下条件。 But I don't understand why the first two examples evaluate to true. 但是我不明白为什么前两个示例评估为正确。
My goal is to require condition3
to be false and then have either conditon1
or condition2
(or both) to be true (but if condition3
is true
then I don't want print statement to execute regardless of how condition1
and condition2
evaluate) 我的目标是要求
condition3
是假的,然后要么 conditon1
或condition2
(或两者)是真实的(但如果condition3
是true
话,我不想print语句不管执行如何condition1
和condition2
计算)
Thanks 谢谢
You said: 你说:
It also gives && higher precedence over ||.
与&|相比,它还给&&更高的优先级。
which means !condition3 && condition1
will be evaluated first. 这意味着
!condition3 && condition1
将首先被评估。
So this 所以这
!condition3 && condition1 || condition2
equals: 等于:
(!condition3 && condition1) || condition2
since condition2
is true
, the expression is true
. 由于
condition2
为true
,因此表达式为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.