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 &&
.
A side note: Java has |= but not an ||=
An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.
|| returns a boolean value by OR'ing two values (Thats why its known as a LOGICAL or)
IE:
Would return true if either A or B is true, or false if they are both false.
| is an operator that performs a bitwise operation on two values. To better understand bitwise operations, you can read here:
http://en.wikipedia.org/wiki/Bitwise_operation
Take a look at:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
| is bitwise inclusive OR
|| is logical OR
The operators
||
and&&
are called conditional operators, while|
and&
are called bitwise operators. They serve different purposes.Conditional operators works only with expressions that statically evaluate to
boolean
on both left- and right-hand sides.Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.
The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it's original state.
Read more: http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk
a | b: evaluate b in any case
a || b: evaluate b only if a evaluates to false