逻辑OR和短路OR运算符有什么区别?

时间:2016-04-10 06:58:54

标签: java logical-operators

  

我得到相同的输出:       a | b =假       a || b =假       a | b =真       a || b =真       a | b =真       a || b =真       a | b =真       a || b =真

What is the difference between these two operators ? 

boolean a = false;  
boolean b = false;  

System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = false;  
b = true;   
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = true;   
b = false;  
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = true;   
b = true;   
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

1 个答案:

答案 0 :(得分:2)

不同之处在于,如果第一个操作数为真,则短路运算符不会计算第二个操作数,而没有短路的逻辑OR总是会计算两个操作数。

你不会在简单测试中看到任何差异,因为假设没有抛出异常,两者都应该给出相同的输出,但是如果你尝试这样的话:

String s = null;
System.out.println("a || b = " + s==null || s.length() == 0 );
System.out.println("a | b = " + s==null | s.length() == 0 );

第一个运算符将为您提供true,而第二个运算符将为您提供NullPointerException,因为只有|运算符才会尝试评估s.length() == 0