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

Logical XOR Operator: ^

Discover the exclusive OR operator that returns true only when operands differ in boolean value.

What You'll Learn

You'll discover the exclusive OR (XOR) operator ^, which returns true only when its two boolean operands have different values.

Understanding XOR: The "Exactly One" Operator

While && requires both operands to be true and || requires at least one to be true, the XOR operator ^ is more selective: it returns true only when exactly one operand is true—not both, not neither.

Think of it like a light switch controlled by two panels at opposite ends of a hallway. The light turns on only when the switches are in different positions. If both are up or both are down, the light stays off.

The XOR Truth Table

Here's how ^ behaves with boolean values:

  • true ^ true → false (both same)
  • true ^ false → true (different!)
  • false ^ true → true (different!)
  • false ^ false → false (both same)

XOR in Action

boolean hasLicense = true;
boolean hasInsurance = false;

// Returns true because they differ
boolean needsAttention = hasLicense ^ hasInsurance;
System.out.println(needsAttention); // true

boolean bothReady = true;
boolean bothChecked = true;

// Returns false because both are the same
boolean mismatch = bothReady ^ bothChecked;
System.out.println(mismatch); // false

When to Use XOR

XOR is useful when you need to detect a difference or ensure conditions are mutually exclusive—exactly one thing should be true, but not both.

Unlike && and ||, XOR does not short-circuit. Both operands are always evaluated, regardless of the first operand's value.

Key Takeaway: The XOR operator ^ returns true when its boolean operands differ (one true, one false) and false when they're the same.