问题
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)
回答1:
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.
回答2:
&&
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.
回答3:
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.
来源:https://stackoverflow.com/questions/20844191/why-is-at-a-higher-precedence-than-java