Why && has a higher priority 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 recently discovered that, in my opinion, there is a little oddity here. Why && and || are at different priority levels? I would suggest that they were on the same level. This demonstrates the above. both statements are true, although an estimate from left to right gives false for the first and true for the second.

Does anyone know the reasons for this?

(By the way, I would just use parentheses here, but it was the old code that raised the question)

+7
java operator-precedence
source share
4 answers

Because in the usual mathematical notation, and ( logical conjunction ) has a higher priority than or ( logical disjunction ).

All non-esoteric programming languages โ€‹โ€‹will reflect the existing convention for these kinds of things for obvious reasons.

+8
source share

&& is the Boolean analog of multiplication ( x && y == x * y ), and || is the Boolean analog of addition ( x || y == (bool)(x + y) ). Since multiplication takes precedence over addition, the same convention is used.

Note that the most common โ€œcanonicalโ€ form for a logical expression is a bunch of or-ed together and-clauses, so this fits well with that.

+8
source share

This is the usual priority order for such statements. Other languages, such as C ++, also have the same priority order. The same is true for mathematical notation, see here .

+2
source share

As far as I know, && i.e. the and-operator operator has higher priority than || ie or-operator in most languages. I do not know a single one with the opposite priority.

-2
source share

All Articles