Cogman
Cogman

Reputation: 2160

Why is && at a higher precedence than || (Java)

    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)

Upvotes: 10

Views: 4209

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

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.

Upvotes: 19

Sneftel
Sneftel

Reputation: 41542

&& 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.

Upvotes: 14

Javier
Javier

Reputation: 12408

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.

Upvotes: 1

Related Questions