How to PROVE the precedence of '&&' and '||' by CODING in java?

If && didn't have higher precedence than ||, then this expression:

a || b && c

would be evaluated like this:

(a || b) && c

To verify if this is the case or not, you can generate all combinations of a, b, and c, and compare the result of these two expressions, to see if they are always equal or not, that is:

  1. For all combinations of a, b, and c
  2. Verify that: (a || b && c) == ((a || b) && c)

Sample code:

for (int i = 0; i < 8; ++i) {
    boolean a = ((i >> 2) & 1) == 1;
    boolean b = ((i >> 1) & 1) == 1;
    boolean c = (i & 1) == 1;
    boolean x1 = (a || b && c);
    boolean x2 = ((a || b) && c);

    if (x1 != x2) {
        System.out.println(String.format("%s %s %s", a, b, c));
        System.out.println(String.format("   %s || %s  && %s => %s", a, b, c, x1));
        System.out.println(String.format("  (%s || %s) && %s => %s", a, b, c, x2));
    }
}

The output:

true false false
   true || false  && false => true
  (true || false) && false => false
true true false
   true || true  && false => true
  (true || true) && false => false

As such, && has higher precedence than ||.


I too had this same question but the answer was practically giving to me. Here is my example:

true || true && false

is equivalent to

true || (true && false)

So with this example it is easy to see that under the hood in Java the logical && has a higher precedence than ||.


Let's take your example expression:

boolExp1 || boolExp2 && boolExp3 || boolExp4

Now we believe that acts as:

boolExp1 || (boolExp2 && boolExp3) || boolExp4

right?

So let's suppose the opposite is true, and it's actually

(boolExp1 || boolExp2) && (boolExp3 || boolExp4)

What values of boolExp1 etc would give us different results?

Well, let's take:

boolExp1 = true
boolExp2 = false
boolExp3 = false
boolExp4 = false

Under the "&& has higher precedence" rules, the result would be true. Under the "|| has higher precedence rules", the result would be false. A quick test shows that the expression evaluates to true, however.

Of course, this doesn't actually prove that && has higher precedence than || - merely that || doesn't have higher precedence than &&. We could consider whether they have equal precedence - and test that with other expressions in a similar way... find a sample expression and values which would give different results under different precedence rules, and test them.

Ultimately though, I prefer:

  • To trust the spec unless I have specific doubts
  • To use parentheses to make my intentions clear

I wouldn't use the first expression "as is" in the first place... because unless you actually know the precedence rules (and I suspect many Java devs don't - I couldn't swear that I'd have got && and || right) you're in the dark. Better to make it explicit and clear where there's any doubt.