为什么我们通常使用||超过|?有什么区别? [英] Why do we usually use || over |? What is the difference?
问题描述
我只是想知道为什么我们通常在两个布尔值之间使用逻辑或||
而不是按位或|
,尽管它们都运行良好.
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()
}
就像Jeremy和Peter提到的那样,短路的另一个好处是空引用检查:
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屋!