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)
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.
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.
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.
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.
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.
&&
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With