← Back to libraryQuestion 72 of 273
⌨️Java CodingBeginner

Swap Two Numbers Without a Temp Variable

📌 Definition:

Exchange two variables without a third temporary variable.

📖 Detailed Explanation:

Arithmetic (a=a+b; b=a-b; a=a-b) or XOR (a^=b; b^=a; a^=b) both avoid a temp. Caveats: arithmetic can overflow, XOR is integer-only, and both zero-out if the two operands are the same variable. In real code a temp (or destructuring/tuple swap) is clearer.

💻 Solutions:
int a = 5, b = 9;
a = a + b;   // 14
b = a - b;   // 5
a = a - b;   // 9
let a = 5, b = 9;
[a, b] = [b, a];   // idiomatic, no temp
// arithmetic: a = a + b; b = a - b; a = a - b;
a, b = 5, 9
a, b = b, a   # tuple swap, no temp
🔑 Key Points:
  • Arithmetic swap can overflow
  • XOR swap is integer-only
  • Both fail if the operands are aliased
  • Prefer a temp / tuple swap in real code
🌍 Real-World Example:

A pure trick question; the value is naming the failure modes (overflow, aliasing) — the "when does this break?" instinct of a strong tester.

🎯 Scenario-Based Interview Question:

A candidate gives the XOR swap. What happens for swap(x, x)?