What does the |= operator do in Java?
a |= x
is a = a | x
, and |
is "bitwise inclusive OR"
Whenever such questions arise, check the official tutorial on operators.
Each operator has an assignment form:
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
>>>=
Where a OP= x
is translated to a = a OP x
And about bitwise operations:
0101 (decimal 5)
OR 0011 (decimal 3)
= 0111 (decimal 7)
The bitwise OR may be used in situations where a set of bits are used as flags; the bits in a single binary numeral may each represent a distinct Boolean variable. Applying the bitwise OR operation to the numeral along with a bit pattern containing 1 in some positions will result in a new numeral with those bits set.
In this case, notification.defaults
is a bit array. By using |=
, you're adding Notification.DEFAULT_VIBRATE
to the set of default options. Inside Notification
, it is likely that the presence of this particular value will be checked for like so:
notification.defaults & Notification.DEFAULT_VIBRATE != 0 // Present
It is a short hand notation for performing a bitwise OR and an assignment in one step.
x |= y
is equivalent to x = x | y
This can be done with many operators, for example:
x += y
x -= y
x /= y
x *= y
etc.
An example of the bitwise OR using numbers.. if either bit is set in the operands the bit will be set in the result. So, if:
x = 0001 and
y = 1100 then
--------
r = 1101
|=
is a bitwise-OR-assignment operator. It takes the current value of the LHS, bitwise-ors the RHS, and assigns the value back to the LHS (in a similar fashion to +=
does with addition).
For example:
foo = 32; // 32 = 0b00100000
bar = 9; // 9 = 0b00001001
baz = 10; // 10 = 0b00001010
foo |= bar; // 32 | 9 = 0b00101001 = 41
// now foo = 41
foo |= baz; // 41 | 10 = 0b00101011 = 43
// now foo = 43