Java中的逻辑运算符优先级 [英] Logical operator precedence in Java

查看:55
本文介绍了Java中的逻辑运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此不满意:

I'm not happy about this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22 . It clearly states the following:

如果操作数表达式没有副作用,则每个运算符都是可交换的."

"Each operator is commutative if the operand expressions have no side effects."

这些运算符具有不同的优先级,&具有最高的优先级,|最低的优先级".

"These operators have different precedence, with & having the highest precedence and | the lowest precedence".

JVM为何不遵守自己的规则.以下面的示例为例.

How come the JVM doesn't comply to it's own rules. Take for instance the following example.

public static void main(String[] args){
    boolean bool = isTrue1() | isFalse1() & isFalse2() ;
    System.out.println("Result : " + bool);
}

public static boolean isFalse1() {
    System.out.println("1 : " + false);
    return false ;
}
public static boolean isFalse2() {
    System.out.println("2 : " + false);
    return false ;
}
public static boolean isTrue1() {
    System.out.println("3 : " + true);
    return true ;
}

结果是:

3 : true
1 : false
2 : false
Result : true

根据& amp;的事实,实际结果应该是运算符在|之前被评估运算符:

While the actual result should be, according to the fact that & operators are evaluated before | operators:

1 : false
2 : false
3 : true
Result : true

关于为什么未正确实施的一些解释会很好.即使在第二部分周围加上括号,也不会使用正确的优先级.

Some explanation would be nice as to why this isn't correctly implemented. Even when adding parentheses around the second part, the correct precedence isn't used.

推荐答案

这些运算符具有不同的优先级,&具有最高的优先级优先级和|最低优先级".

"These operators have different precedence, with & having the highest precedence and | the lowest precedence".

仅仅因为它们具有更高的优先级,并不意味着它们的操作数将首先被评估.

Just because they have higher precedence, doesn't mean their operands will be evaluated first.

boolean bool = isTrue1() | isFalse1() & isFalse2() ;

等同于

boolean bool = isTrue1() | ( isFalse1() & isFalse2() ) ;

这是所有优先事项.

按照Java语言规范的规定,对运算符操作数进行求值从左到右.

As the Java Language Specification says, operator operands are evaluated left to right.

Java编程语言保证以下操作数运营商似乎是按照特定的评估顺序进行评估的,即从左到右.

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

这篇关于Java中的逻辑运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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