Alex K
Alex K

Reputation: 73

Java: OR Operator after AND in "If" Statement

Based on this and this answer Java employs short circuiting with regard to && and || operators. It also gives && higher precedence over ||. Yet the following code evaluates to 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?

If I add parentheses around the first condition it still evaluates to true:

    if ( (!condition3) && condition1 || condition2 ) {
        System.out.println("Condition is true");
    }

I understand why this code evaluates to true:

    if ( condition1 || condition2 && !condition3) {
        System.out.println("Condition is true");
    }

Because once Java encounters the || after condition1 it doesn't even bother checking the following conditions. 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)

Thanks

Upvotes: 2

Views: 11110

Answers (1)

xingbin
xingbin

Reputation: 28289

You said:

It also gives && higher precedence over ||.

which means !condition3 && condition1 will be evaluated first.

So this

!condition3 && condition1 || condition2

equals:

(!condition3 && condition1) || condition2

since condition2 is true, the expression is true.

Upvotes: 10

Related Questions