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

前端 未结 5 2122
长发绾君心
长发绾君心 2020-12-24 10:28

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

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


        
5条回答
  •  星月不相逢
    2020-12-24 10:31

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

提交回复
热议问题