Bitwise Assignment Operators: &=, |=, ^=, <<=, >>=, >>>=
You'll learn how to combine bitwise operations with assignment in a single, efficient step.
What Are Bitwise Assignment Operators?
Just like arithmetic compound assignments (+=, -=), Java provides shorthand operators that perform a bitwise operation and assign the result back to the variable in one step. Instead of writing x = x & mask, you can write x &= mask.
The Six Bitwise Assignment Operators
Each bitwise operator has a compound assignment version:
&=— Bitwise AND assignment:x &= ymeansx = x & y|=— Bitwise OR assignment:x |= ymeansx = x | y^=— Bitwise XOR assignment:x ^= ymeansx = x ^ y<<=— Left shift assignment:x <<= 2meansx = x << 2>>=— Signed right shift assignment:x >>= 2meansx = x >> 2>>>=— Unsigned right shift assignment:x >>>= 2meansx = x >>> 2
Simple Examples
int flags = 0b1010;
flags &= 0b1100; // flags is now 0b1000 (AND operation)
int bits = 0b0011;
bits |= 0b1000; // bits is now 0b1011 (OR operation)
int value = 5;
value <<= 2; // value is now 20 (shifted left by 2 positions)
Why Use Them?
These operators make your code more concise and clearly express "modify this variable using a bitwise operation." They're especially useful when toggling flags, applying masks, or performing repeated bit manipulations.
Key Takeaway: Bitwise assignment operators combine bit manipulation with assignment, letting you write x &= mask instead of x = x & mask for cleaner, more efficient code.