Java Program to Swap Two Numbers Using a Temporary Variable
Swapping two numbers means exchanging their values: if a is 10 and b is 20, after the swap a is 20 and b is 10.
You cannot simply write a = b; b = a;. The first line overwrites the old value of a, so both variables end up as 20. A temporary variable keeps a copy of one value while the other is moved.
1. How the Swap Works
| Step | Statement | a | b | temp |
|---|---|---|---|---|
| Start | 10 | 20 | - | |
| 1 | temp = a; | 10 | 20 | 10 |
| 2 | a = b; | 20 | 20 | 10 |
| 3 | b = temp; | 20 | 10 | 10 |
2. Swap Two Numbers Using a Temporary Variable
public class SwapWithTemp {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swapping: a = " + a + ", b = " + b);
int temp = a; // save a
a = b; // copy b into a
b = temp; // copy the saved value into b
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
Output
Before swapping: a = 10, b = 20 After swapping: a = 20, b = 10
3. Swap Two Numbers with User Input
The same three lines work for any type. This version reads two double values, so decimal numbers can be swapped too.
import java.util.Scanner;
public class SwapWithTempInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = scanner.nextDouble();
System.out.print("Enter second number: ");
double second = scanner.nextDouble();
scanner.close();
double temp = first;
first = second;
second = temp;
System.out.println("After swapping: first = " + first + ", second = " + second);
}
}
Output (with sample input)
Enter first number: 1500 Enter second number: 30.5 After swapping: first = 30.5, second = 1500.0
4. Summary
- Swapping exchanges the values of two variables.
temp = a; a = b; b = temp;is the standard, always-safe way to swap.- Writing
a = b; b = a;loses the original value ofa. - The temporary-variable method works for every type: numbers, strings and objects.
Related Programs
Was this tutorial helpful?