No, |=
and &=
do not shortcircuit, because they are the compound assignment version of &
and |
, which do not shortcircuit.
JLS 15.26.2 Compound Assignment Operators
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
Thus, assuming boolean &
, the equivalence for isFoobared &= methodWithSideEffects()
is:
isFoobared = isFoobared & methodWithSideEffects(); // no shortcircuit
On the other hand &&
and ||
do shortcircuit, but inexplicably Java does not have compound assignment version for them. That is, Java has neither &&=
nor ||=
.
See also
- Shortcut “or-assignment” (|=) operator in Java
- What’s the difference between | and || in Java?
- Why doesn’t Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=)
What is this shortcircuiting business anyway?
The difference between the boolean
logical operators (&
and |
) compared to their boolean
conditional counterparts (&&
and ||
) is that the former do not “shortcircuit”; the latter do. That is, assuming no exception etc:
&
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 tofalse
- (because no matter what the right operand evaluates to, the entire expression is
false
)
- (because no matter what the right operand evaluates to, the entire expression is
- The left operand of
||
evaluates totrue
- (because no matter what the right operand evaluates to, the entire expression is
true
)
- (because no matter what the right operand evaluates to, the entire expression is
- The left operand of