Java Program to Swap Two Numbers Without a Temporary Variable
Two numbers can be swapped without a third variable by storing information about both values in one of them. This page shows three tricks: addition and subtraction, the XOR operator, and multiplication and division. They are popular interview questions, but each has limits, which are explained below.
1. Swap Using Addition and Subtraction
With a = 10 and b = 20:
a = a + b;makesa30 (the sum of both).b = a - b;makesb30 - 20 = 10 (the olda).a = a - b;makesa30 - 10 = 20 (the oldb).
public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
Output
Before swapping: a = 10, b = 20 After swapping: a = 20, b = 10
2. Swap Using the XOR Operator
The bitwise XOR operator ^ has the property that x ^ y ^ y == x. Applying it three times swaps the values without any risk of overflow. This version reads the numbers from the user.
import java.util.Scanner;
public class SwapXor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();
scanner.close();
a = a ^ b;
b = a ^ b; // (a ^ b) ^ b = a
a = a ^ b; // (a ^ b) ^ a = b
System.out.println("After swapping: first = " + a + ", second = " + b);
}
}
Output (with sample input)
Enter first number: 2000 Enter second number: 4000 After swapping: first = 4000, second = 2000
3. Swap Using Multiplication and Division
The same idea works with * and /, but it fails if either number is 0 (division by zero) and can overflow for large values. It is shown here only for completeness.
public class SwapMultiply {
public static void main(String[] args) {
int a = 6;
int b = 9;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a * b; // 54
b = a / b; // 6
a = a / b; // 9
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
Output
Before swapping: a = 6, b = 9 After swapping: a = 9, b = 6
4. Summary
a = a + b; b = a - b; a = a - b;swaps two numbers without a third variable.- The XOR version
a ^= b; b ^= a; a ^= b;works for integers and never overflows. - The multiply and divide version fails when a value is 0.
- In real code, a temporary variable is clearer and works for every type.
Related Programs
Was this tutorial helpful?