I know what &
and |
does - it evaluates both sides (or all conditions if more than 2) - but I can't say I've used those two operators for a very long time, I always used &&
and ||
.
e.g. (a != null) & (a.length == 1)
would throw if we're checking the length of a
after we know it's null, and obviously (a != null) && (a.length == 1)
would just return false if a
was null without the need to check if the length of a
is 1. I also know there's a slight performance benefit to using &&
and ||
if you have many conditions to check returning true/false at condition 2/100 is faster than evaluating all 100 knowing it's true/false at condition 2.
What situations would require the single &
and |
operands?
&&
and ||
is the logical AND or OR between two predicates. This is why it could be more efficient as with logical AND or OR we can do Short-circuit evaluation.
On the other side, &
and |
applies a bitwise AND or OR. This does not use Short-circuit evaluation. The use of this is generally less to do with the checking against predicates, and more to do with bit based operations such as bit-masking.