Search code examples
javaoperator-precedenceunary-operatorlogical-or

Java's logical OR operator does not evaluate right hand side despite that right hand side has a unary operator?


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 (||).


Solution

  • 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:

    if (!x.equals(y) || y.equals(z))
    

    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:

    if (!(x.equals(y) || y.equals(z)))
    

    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.