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

The Bitwise XOR Operator (^)

How ^ compares corresponding bits and returns 1 only when bits differ.

The Bitwise XOR Operator (^)

What you'll learn: How the bitwise XOR operator compares corresponding bits and returns 1 only when the bits differ.

Understanding XOR: The "Difference Detector"

The bitwise XOR (exclusive OR) operator ^ examines each pair of corresponding bits in two numbers and follows a simple rule: it returns 1 when the bits are different and 0 when they're the same.

Think of XOR like a light switch controlled by two people. The light is ON (1) only when exactly one person has their switch flipped—if both switches match (both on or both off), the light stays OFF (0).

The XOR Truth Table

For each bit position:

  • 0 ^ 0 = 0 (same → 0)
  • 0 ^ 1 = 1 (different → 1)
  • 1 ^ 0 = 1 (different → 1)
  • 1 ^ 1 = 0 (same → 0)

Example in Action

int a = 12;  // Binary: 1100
int b = 10;  // Binary: 1010
int result = a ^ b;

// Bit-by-bit comparison:
//   1100
// ^ 1010
// ------
//   0110  (which is 6 in decimal)

System.out.println(result);  // Outputs: 6

How It Differs from Other Bitwise Operators

  • AND (&): Returns 1 only when both bits are 1
  • OR (|): Returns 1 when at least one bit is 1
  • XOR (^): Returns 1 only when bits differ

XOR is particularly useful for detecting differences, toggling bits, and certain cryptographic operations where you need to compare or flip data based on a pattern.

Key Takeaway: The bitwise XOR operator ^ compares corresponding bits and produces 1 when they differ, 0 when they match—making it perfect for detecting differences between binary values.