Given that:
Object x = null;
Consider code snippet #1:
if (x == null || !x.equals(new Object()))
System.out.println("I print!");
Code snippet #1 does not throw a NullPointerException
as I first thought it should have. I can provoke the exception with a little bit of help from the |
operator. Code snippet #2:
if (x == null | !x.equals(new Object()))
System.out.println("This will throw a NullPointerException..");
How come then that my first code snippet never evaluated the right expression that has a unary NOT operator in it (the exclamation !
)? According to.. well all web sites out there.. the unary NOT operator has higher precedence that that of the logical OR operator (||
).
Yes it's true. But the precedence thing will come into effect, if you use NOT on the first expression of logical OR.
Consider the condition:
In this case, the negation will be applied first on the result of
x.equals(y)
, before the logical OR. So, had the precedence of||
been greater than!
, then the expression would have been evaluated as:But it's not. As you know why.
However, if the NOT operator is on the second expression, the precedence is not a point here. The first expression will always be evaluated first before the 2nd expression. And short-circuit behaviour will come into play.