[英]Operator precedence for multiple parentheses in Java
For example, if currNode.left
and currNode.right
were null, I would want the if statement to break before evaluating any further than currNode.left != null
, but the following if statement throw a null pointer error because it's evaluating the statement in the parentheses first:例如,如果
currNode.left
和currNode.right
为空,我希望 if 语句在评估任何比currNode.left != null
之前中断,但以下 if 语句抛出空指针错误,因为它正在评估中的语句首先是括号:
if (currNode.left != null && currNode.right != null && (currNode.left.val == x && currNode.right.val == y) || (currNode.left.val == y && currNode.right.val == x))
where as an extra pair of parentheses at the end gives the desired behavior:其中作为末尾的一对额外括号给出了所需的行为:
if (currNode.left != null && currNode.right != null && ((currNode.left.val == x && currNode.right.val == y) || (currNode.left.val == y && currNode.right.val == x)))
I know ()
is evaluated before &&
, but I'm not sure what is going on here.我知道
()
在&&
之前被评估,但我不确定这里发生了什么。
The logical OR ||
逻辑 OR
||
has lower precedence than the logical AND &&
.具有比逻辑 AND
&&
低的优先级。 So:所以:
A && B || C && D
is equivalent to:相当于:
(A && B) || (C && D)
whereas what inside the parentheses are evaluated first.而括号内的内容首先被评估。
Read more about operators in Java:阅读有关 Java 运算符的更多信息:
EDIT:编辑:
In your first example:在你的第一个例子中:
A && B && (C && D) || (E && F)
this is evaluated as follows:评估如下:
= A && B && (C && D) || (E && F)
= R1 && (C && D) || (E && F)
= R1 && R2 || (E && F)
= R1 && R2 || R3
= R4 || R3
= R5
In your second example:在你的第二个例子中:
A && B && ((C && D) || (E && F))
this is evaluated as follows:评估如下:
= A && B && ((C && D) || (E && F))
= R1 && ((C && D) || (E && F))
= R1 && ( R2 || (E && F))
= R1 && ( R2 || R3 )
= R1 && R4
= R5
Note that &&
and ||
注意
&&
和||
are short-circuit operators, which means the right operand will not be evaluated if the result can be inferred from evaluating the left operand.是短路运算符,这意味着如果可以从评估左操作数中推断出结果,则不会评估右操作数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.