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

问题描述

我对此不满意: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22 .它明确指出以下内容:

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:

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.

推荐答案

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

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中的逻辑运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:40