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

北战南征 提交于 2019-11-30 04:05:12

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!