Swap Two Numbers Without Third Variable in Java
Problem
Two numbers can be swapped without any extra storage by temporarily combining their values, then separating them back out.
Given two integers, swap their values without using a third variable.
Java Program
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
int a = 5;
int b = 10;
a = a + b; // a now holds the combined sum
b = a - b; // b becomes a's original value
a = a - b; // a becomes b's original value
System.out.println("a=" + a + ", b=" + b);
}
}Output
Core Logic
Addition and subtraction can swap two values without any extra variable, by temporarily storing both values' combined sum in one of them.
- 1
a = a + bstores the combined sum (15) ina, soanow holds both original values added together. - 2
b = a - bsubtracts the originalb(10) from that sum (15), leavingbwitha's original value (5). - 3
a = a - bsubtracts the newb(5) from the sum (15), leavingawithb's original value (10).
a becomes 15, then b becomes 5, then a becomes 10 — ending at a=10, b=5.Key Point: This trick can silently overflow if a + b exceeds int's range — for values close to Integer.MAX_VALUE, the temp-variable approach is the safer choice.
Key Concepts
Approach 2: Swap Using XOR
public class SwapUsingXor {
public static void main(String[] args) {
int a = 5;
int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a=" + a + ", b=" + b);
}
}
Output
Core Logic
The bitwise XOR operator can swap two integers without any overflow risk, using the fact that XOR-ing a value with itself cancels it out.
- 1
a = a ^ bcombines both original values intoausing bitwise XOR. - 2
b = a ^ bXORs that combined value with the originalb, which cancels outb's own bits and leavesa's original value inb. - 3
a = a ^ bXORs the combined value with the newb(a's original value), which cancels those bits out and leavesb's original value ina.
a becomes 15 (1111), then b becomes 5, then a becomes 10 — ending at a=10, b=5.Key Point: Unlike the addition/subtraction trick, XOR swap never overflows since it operates on bits directly — but it silently fails if a and b are the same variable (not just equal values), zeroing both out.