为什么我们通常使用`||`而不是`|`,有什么区别? [英] Why do we usually use `||` not `|`, what is the difference?
问题描述
我只是想知道为什么我们通常在两个布尔值之间使用逻辑OR ||
而不是按位OR |
,虽然他们都运作良好。
I'm just wondering why we usually use logical OR ||
between two booleans not bitwise OR |
, though they are both working well.
我的意思是,看看以下内容:
I mean, look at the following:
if(true | true) // pass
if(true | false) // pass
if(false | true) // pass
if(false | false) // no pass
if(true || true) // pass
if(true || false) // pass
if(false || true) // pass
if(false || false) // no pass
我们可以使用 |
而不是 ||
?同样的事情与&
和&&
。
Can we use |
instead of ||
? Same thing with &
and &&
.
推荐答案
如果您使用 ||
和&&
表格,而不是这些运算符的 |
和&
形式,Java不会费心去评估右边的操作数单独。
If you use the ||
and &&
forms, rather than the |
and &
forms of these operators, Java will not bother to evaluate the right-hand operand alone.
这是一个问题,如果你想要短路评估或者不是 - 大多数你想要的时间。
It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.
说明短路效益的好方法是考虑以下示例。
A good way to illustrate the benefits of short-circuiting would be to consider the following example.
Boolean b = true;
if(b || foo.timeConsumingCall())
{
//we entered without calling timeConsumingCall()
}
正如杰里米和彼得所提到的,短路的另一个好处是空参考检查:
Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:
if(string != null && string.isEmpty())
{
//we check for string being null before calling isEmpty()
}
这篇关于为什么我们通常使用`||`而不是`|`,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!