Java boolean |= operator
The bitwise logic operators will have the same effect of "normal" logic operators on booleans.
From Java Language Specification 15.22:
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The only real difference is that bitwise operators cant be used to short-circuit evaluation.
For example, this code will throw NullPointerException
:
Boolean b1 = new Boolean(true);
Boolean b2 = null;
if (b1 || b2) {
//no null pointer here;
}
if (b1 | b2) {
//null pointer here;
}
From the 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.15.22.2. Boolean Logical Operators
&
,^
, and|
When both operands of a
&
,^
, or|
operator are of typeboolean
orBoolean
, then the type of the bitwise operator expression isboolean
. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.For
|
, the result value is false if both operand values are false; otherwise, the result is true.
This means that
val |= somethingElse();
is strictly equivalent to
val = val | somethingElse();
(assuming somethingElse()
returns boolean
or Boolean
).
I'd be curious if right operand is evaluated if left value already is true.
Yes, it would be evaluated, since |
does not short-circuit:
15.7.2. Evaluate Operands before Operation
The Java programming language guarantees that every operand of an operator (except the conditional operators
&&
,||
, and? :
) appears to be fully evaluated before any part of the operation itself is performed.15.24. Conditional-Or Operator
||
Thus,
||
computes the same result as|
onboolean
orBoolean
operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2 for the definition of |
. See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2 for the defintion of |=
. The definitions are just what you would think.
What surprises me is the lack of a ||=
operator.