Bitwise Compound Assignment Operators
What you'll learn: How to combine bitwise operations with assignment using shorthand operators for cleaner, more concise code.
The Core Idea
You've already learned bitwise operators (&, |, ^, <<, >>, >>>) and you've seen compound assignment with arithmetic (+=, -=). Now Java lets you combine these concepts! Instead of writing x = x & mask, you can write x &= mask. This shorthand applies a bitwise operation and assigns the result back to the same variable in one step.
The Six Bitwise Compound Operators
&=(AND and assign):flags &= maskmeansflags = flags & mask|=(OR and assign):flags |= maskmeansflags = flags | mask^=(XOR and assign):flags ^= maskmeansflags = flags ^ mask<<=(left shift and assign):x <<= 2meansx = x << 2>>=(signed right shift and assign):x >>= 3meansx = x >> 3>>>=(unsigned right shift and assign):x >>>= 1meansx = x >>> 1
Why Use Them?
These operators make bit manipulation code shorter and clearer, especially when working with bit flags. Instead of repeating the variable name, you express your intent directly: "modify this variable using this bitwise operation."
int permissions = 0b1010; // Read and Execute
// Without compound operator
permissions = permissions | 0b0100; // Add Write permission
// With compound operator (cleaner!)
permissions |= 0b0100; // Add Write permission
Both versions do the same thing, but the compound form is more concise and reduces typing errors.
Key Takeaway: Bitwise compound assignment operators (&=, |=, ^=, <<=, >>=, >>>=) combine a bitwise operation with assignment, providing a shorthand that makes bit manipulation code cleaner and more readable.