The |=
is a compound assignment operator (JLS 15.26.2) for the boolean logical operator |
(JLS 15.22.2); not to be confused with the conditional-or ||
(JLS 15.24). There are also &=
and ^=
corresponding to the compound assignment version of the boolean logical &
and ^
respectively.
In other words, for boolean b1, b2
, these two are equivalent:
b1 |= b2;
b1 = b1 | b2;
The difference between the logical operators (&
and |
) compared to their conditional counterparts (&&
and ||
) is that the former do not "shortcircuit"; the latter do. That is:
&
and |
always evaluate both operands
&&
and ||
evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
- The left operand of
&&
evaluates to false
- (because no matter what the right operand evaluates to, the entire expression is
false
)
- The left operand of
||
evaluates to true
- (because no matter what the right operand evaluates to, the entire expression is
true
)
So going back to your original question, yes, that construct is valid, and while |=
is not exactly an equivalent shortcut for =
and ||
, it does compute what you want. Since the right hand side of the |=
operator in your usage is a simple integer comparison operation, the fact that |
does not shortcircuit is insignificant.
There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.
It is unfortunate that unlike some other languages, Java does not have &&=
and ||=
. This was discussed in the question Why doesn’t Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=).