In this Java program, we will learn how to swap two numbers without using a third or temporary variable.
For example, if:
a = 10
b = 20
After swapping:
a = 20
b = 10
Java Program
We can swap two numbers using arithmetic operators without requiring a third variable.
import java.util.Scanner;
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println("Before Swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After Swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
sc.close();
}
}
Output
Enter first number: 10
Enter second number: 20
Before Swapping:
a = 10
b = 20
After Swapping:
a = 20
b = 10
Explanation
The swapping is performed using three arithmetic operations:
a = a + b;
b = a - b;
a = a - b;
Suppose:
a = 10
b = 20
The first statement adds both values:
a = 10 + 20 = 30
Now:
a = 30
b = 20
The second statement calculates the original value of a:
b = 30 - 20 = 10
Now:
a = 30
b = 10
Finally, the third statement calculates the original value of b:
a = 30 - 10 = 20
Therefore:
a = 20
b = 10
The two values have been successfully swapped without using a third variable.
Alternative Method Using XOR
For integer values, two numbers can also be swapped without a third variable using the XOR (^) operator:
a = a ^ b;
b = a ^ b;
a = a ^ b;
However, the addition/subtraction approach is generally easier for beginners to understand.
Important Note
The addition/subtraction method can cause integer overflow if a + b exceeds the range of the int data type. For production code, using a temporary variable is usually clearer and safer.
Key Points
- No third or temporary variable is used.
- The values are swapped using arithmetic operations.
- The program works with Java 8 and later versions.
- XOR can also be used as an alternative for integer values.
Conclusion
Swapping two numbers without a third variable is a common Java programming interview question. The addition and subtraction method provides a simple way to exchange two integer values without using an additional variable.