Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ^ operator in Java is the Exclusive OR (XOR) operator. It functions as a bitwise operator when applied to integer primitives and as a logical operator when applied to boolean primitives. It evaluates to 1 (or true) if and only if the operands are strictly different, and 0 (or false) if they are identical.

Bitwise XOR (Integer Types)

When applied to integral data types (byte, short, int, long, char), the ^ operator performs a bit-by-bit comparison of the binary representations of the operands. Bitwise Truth Table:
  • 0 ^ 0 yields 0
  • 0 ^ 1 yields 1
  • 1 ^ 0 yields 1
  • 1 ^ 1 yields 0
Syntax Visualization:
int a = 5;      // Binary: 0000 0101
int b = 3;      // Binary: 0000 0011

int result = a ^ b; 
// Bitwise evaluation:
//   0000 0101
// ^ 0000 0011
// --------
//   0000 0110  -> Decimal: 6

System.out.println(result); // Outputs: 6
Note: If operands are of different sizes (e.g., int and long), Java performs binary numeric promotion, widening the smaller type to match the larger type before applying the XOR operation.

Logical XOR (Boolean Types)

When applied to boolean operands, the ^ operator evaluates whether the two boolean expressions have different truth values. Crucially, unlike the conditional logical operators (&& and ||), the logical ^ operator does not short-circuit. Both the left-hand and right-hand operands are strictly evaluated before the XOR operation is applied. Logical Truth Table:
  • false ^ false yields false
  • false ^ true yields true
  • true ^ false yields true
  • true ^ true yields false
Syntax Visualization:
boolean x = true;
boolean y = false;

boolean result1 = x ^ y;     // Evaluates to true
boolean result2 = x ^ true;  // Evaluates to false

// Both methodA() and methodB() will execute because ^ does not short-circuit
boolean result3 = methodA() ^ methodB(); 

Compound Assignment (^=)

Java provides a compound assignment operator for XOR, which applies the operation and assigns the result to the left-hand operand. It includes an implicit cast to the type of the left-hand operand. Syntax Visualization:
int val = 10;   // Binary: 1010
val ^= 4;       // Binary: 0100
// val is now 14 (Binary: 1110)

boolean flag = true;
flag ^= true;   
// flag is now false
Master Java with Deep Grasping Methodology!Learn More