为什么是&&优先级高于|| (Java) [英] Why is && at a higher precedence than || (Java)

查看:94
本文介绍了为什么是&&优先级高于|| (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    boolean a = true;
    boolean b = true;
    boolean c = false;

    System.out.println(a || b && c); // true
    System.out.println(b && c || a); // true

我最近才发现我认为这里有些奇怪.为什么&&||处于不同的优先级?我本以为它们处于同一水平.以上说明了这一点.即使从左到右的求值方法对第一个给出的结果都是假,而第二个则给出的是真,这两个陈述都是正确的.

有人知道背后的原因吗?

(顺便说一句,我会在这里使用大量的括号,但这是提出问题的旧代码)

解决方案

由于采用传统的数学符号,所以and(逻辑合取).

出于明显的原因,所有非深奥的编程语言都将反映这种事情的现有约定.

    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)

解决方案

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.

这篇关于为什么是&&优先级高于|| (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆