Java Operators : |= bitwise OR and assign example

Java Operators : |= bitwise OR and assign example

a |= b is the same as a = a | b

a | b is a bitwise operator if both operands are integral types (int, short, etc…). If both operands are booleans, then its is a boolean or.

When both a and b are booleans, the difference between a | b and a || b is that in the first, both sides are always evaluated, in the later b is only evaluated if a is false. It is sort of a “shortcut” operator.

This is useful for situations like this:

if (a == null || a.equals(b)) { .. do something .. } // works if (a == null | a.equals(b)) { .. do something .. } // NPE if a is null

On the other hand, || actually is implemented as another conditional jump in the bytecode/machine-code. In some cases, it may be faster to evaluate boolean conditions using the | operator to avoid the additional jump (and thus branch predition, etc…). Definitely something for low-level micro-benchmarking to figure out which is better (and usually not important in most applications).

When you do a |= b you are always evaluating both a and b. It doesn’t really make sense to have an a ||= b operators, since the equivalent a = a || b would translate to:

if (a) a = true; else if (b) a = true else a = false;

…due to the conditional nature of || evaluation. In other words, b would not be evaluated if a was already true.


Leave a Reply