Course contentsShow
← Java
Lesson 124 of 2,8703. Operators and ExpressionsFree lesson

Bitwise Compound Assignment Operators

Using &=, |=, ^=, <<=, >>=, and >>>= for concise bitwise operations.

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 &= mask means flags = flags & mask
  • |= (OR and assign): flags |= mask means flags = flags | mask
  • ^= (XOR and assign): flags ^= mask means flags = flags ^ mask
  • <<= (left shift and assign): x <<= 2 means x = x << 2
  • >>= (signed right shift and assign): x >>= 3 means x = x >> 3
  • >>>= (unsigned right shift and assign): x >>>= 1 means x = 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.