Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 481
Cogman Avatar asked Dec 30 '13 17:12

Cogman


People also ask

Why is the sky blue short answer?

The Short Answer: Sunlight reaches Earth's atmosphere and is scattered in all directions by all the gases and particles in the air. Blue light is scattered more than the other colors because it travels as shorter, smaller waves. This is why we see a blue sky most of the time.

What is the real colour of sky?

Our sky is actually purple Purple light has higher energy, and gets scattered more than blue. But the answer to why we see blue skies isn't a matter of physics; it's an answer for physiology.

Why is Earth's sky blue in daytime?

The Short Answer: Gases and particles in Earth's atmosphere scatter sunlight in all directions. Blue light is scattered more than other colors because it travels as shorter, smaller waves. This is why we see a blue sky most of the time.

Why is the sky not violet?

This is because the sun emits a higher concentration of blue light waves in comparison violet. Furthermore, as our eyes are more sensitive to blue rather than violet this means to us the sky appears blue.


2 Answers

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.

like image 94
Oliver Charlesworth Avatar answered Sep 19 '22 19:09

Oliver Charlesworth


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

like image 30
Sneftel Avatar answered Sep 18 '22 19:09

Sneftel