Java中的运算符

Java中的运算符,java,operators,Java,Operators,我正在学习Java中的运算符,我有一个无法解决的问题 public static boolean first(){ System.out.println("first"); return true; } public static boolean second(){ System.out.println("second"); return true; } public static boolean third

我正在学习Java中的运算符,我有一个无法解决的问题

    public static boolean first(){
       System.out.println("first");
       return true;
   }
   public static boolean second(){
       System.out.println("second");
       return true;
   }
   public static boolean third(){
       System.out.println("third");
       return true;
   }
    public static void main(String[] args) {
       if(first() && second() | third()){
           //Do something
       }
    }
输出为“第一、第二、第三”。我认为应该是“第二-第三-第一”,因为|大于&。我不知道我的错误在哪里,但显然有一个。

first()&&second()| third()
由于运算符优先级,被计算为
first()&&second()| third())
。计算从左到右进行,因此首先计算
first()
,然后计算
(second()| third())
。在计算后一个术语时,将计算两个参数(再次从左侧开始),因为
first()
true
,并且
运算符没有短路

您的意思是使用单个
|


不太特殊的
first()&&second()| | third()
被评估为
(first()&&second())| | third()
first()
second()
都在此实例中进行计算(并按顺序),因为
first()
返回
true
。由于
second()
也返回
true
third()
将不会被计算。

不要混淆运算符优先级和计算顺序:

Java编程语言保证运算符的操作数按特定的求值顺序求值,即从左到右

因此,输出为:

first
second
third
由于方法调用在表达式中的顺序:

first() && second() | third()

实际使用的运算符(
&&
|
|
)与顺序无关。不同的运算符选择可能会导致某些行无法打印,但打印的行将按此顺序进行。

键入
if(first()&&second()| | third()){
我认为求值顺序比这里的优先级或短路更重要。OP期望(并看到)所有三个表达式都进行了计算;这似乎是他们不期望的计算顺序。