2

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

xingbin
  • 27,410
  • 9
  • 53
  • 103
Alex K
  • 73
  • 1
  • 5
  • *"My goal is to require condition3 to be false and then have either conditon1 or condition2 (or both) to be true"* `if ((!condition3)&&(condition1||condition2))` – Timothy Truckle Sep 05 '18 at 16:21
  • OK so I missed parentheses around `condition1 || condition2 `. But why is it not sufficient (to give `!condition3` higher precedence) to add parentheses only around `!condition3 ` ? – Alex K Sep 05 '18 at 16:25
  • 1
    "higer precedence" means that this parts "stay closer" then the rest. The *result* of `&&` becomes one side of the `||` – Timothy Truckle Sep 05 '18 at 16:34

1 Answers1

10

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.

xingbin
  • 27,410
  • 9
  • 53
  • 103