Question

    boolean a = true;
    boolean b = true;
    boolean c = false;

    System.out.println(a || b && c); // true
    System.out.println(b && c || a); // true

I just recently discovered what I thought was a bit of an oddity here. Why is it that && and || are at different precedence levels? I would have assumed that they were at the same level. The above demonstrates it. both statements are true even though a left to right evaluation would give false for the first and true for the second.

Does anyone know the reasoning behind this?

(BTW, I would have just used a load of parentheses here, but it was old code which brought up the question)

Was it helpful?

Solution

Because in conventional mathematical notation, and (logical conjunction) has higher precedence than or (logical disjunction).

All non-esoteric programming languages will reflect existing convention for this sort of thing, for obvious reasons.

OTHER TIPS

&& is the boolean analogue of multiplication (x && y == x * y), while || is the boolean analogue of addition (x || y == (bool)(x + y)). Since multiplication has a higher precedence than addition, the same convention is used.

Note that the most common "canonical" form for boolean expression is a bunch of or-ed together and-clauses, so this dovetails well with that.

That is the customary order of precedence for such operators. Other languages, such as C++ also have the same precedence order. The same holds for mathematical notation, see here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top