Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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 &&.

1 Answer

0 votes
by (46k points)

If you apply the || and && forms, preferably than the | and & forms of these operators, Java will not worry to evaluate the right-hand operand alone.

It's a subject of if you want to short-circuit the evaluation or not -- most of the time you require to.

A good way to explain the benefits of short-circuiting would be to consider the subsequent example.

Boolean b = true;

if(b || foo.timeConsumingCall())

{

   //we entered without calling timeConsumingCall()

}

Another benefit, for short-circuiting is the null reference try:

if(string != null && string.isEmpty())

{

    //we check for string being null before calling isEmpty()

}

more info

Related questions

Browse Categories

...