Alex Rivera | Logout

Is there a difference between using a logical operator or a bitwise operator in an if block in Java?

Asked 2012-06-22T12:50:50.433
16

The contents of both of the following if blocks should be executed:

if( booleanFunction() || otherBooleanFunction() ) {...}
if( booleanFunction() | otherBooleanFunction() ) {...}

So what's the difference between using | or using ||?

Note: I looked into this and found my own answer, which I included below. Please feel free to correct me or give your own view. There sure is room for improvement!

Edit
Report

2 Answers

8

for programmers, there is only one difference.

  1. your logical operators are logical ones,i.e. they test only one condition and get result based on that.

booleanFunction() || otherBooleanFunction() will be true if either is true. likewise, booleanFunction() && otherBooleanFunction() will be false if either is false. So, why test the other one. that's what logical operators do.

But bitwise ones check both. A frequent application of this concept is as follows.

if(someObject != null && someObject.somemethod())

So, in this case if you replace && by & then wait for a disaster. You will get nasty NullPointerException soon...

answered 2012-06-22T13:00:09.673
4
if( booleanFunction() || otherBooleanFunction() ) {...}

In this condition if booleanFunction() returns true then otherBooleanFunction() would not be executed.

if( booleanFunction() | otherBooleanFunction() ) {...}

But in bitwise operator both functions - booleanFunction() and otherBooleanFunction() would be executed no matter booleanFunction() returns true or false

answered 2012-06-22T12:57:44.110

Your Answer