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.
usually I use when there is pre increment and post increment operator. Look at the following code:
output:
both
if
blocks are same but result is different. when there is|
, both the conditions will be evaluated. But if it is||
, it will not evaluate second condition as the first condition is already true.Java operators
| is bitwise or, || is logical or.
Non short-circuiting can be useful. Sometimes you want to make sure that two expressions evaluate. For example, say you have a method that removes an object from two separate lists. You might want to do something like this:
If your method instead used the conditional operand, it would fail to remove the object from the second list if the first list returned false.
It's not amazingly useful, and (as with most programming tasks) you could achieve it with other means. But it is a use case for bitwise operands.
After carefully reading this topic is still unclear to me if using
|
as a logical operator is conform to Java pattern practices.I recently modified code in a pull request addressing a comment where
had to be changed to
What is the actual accepted version?
Not interested in a vote but more in finding out the standard?! Both code versions are compiling and working as expected.