user22261
user22261

Reputation: 47

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:

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.

Upvotes: 1

Views: 142

Answers (1)

Eng.Fouad
Eng.Fouad

Reputation: 117589

The logical OR || has lower precedence than the logical 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:


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.

Upvotes: 1

Related Questions