Swap Two Numbers in Java - With and Without Temp Variable
Learn different ways to swap two numbers in Java. Using temporary variable and without using it.
Last updated: 11 January 2026
Method 1: Using Temporary Variable
The standard and easiest way.
Main.javaRun in Compiler →
public class SwapNumbers {
public static void main(String[] args) {
int first = 10, second = 20;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
int temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}Output:
--Before swap-- First number = 10 Second number = 20 --After swap-- First number = 20 Second number = 10
Explanation
A temporary variable holds the value of first number while we overwrite first with second.
Method 2: Without Temporary Variable
Using arithmetic operations.
Main.javaRun in Compiler →
public class SwapNumbers {
public static void main(String[] args) {
int first = 10, second = 20;
first = first - second;
second = first + second;
first = second - first;
System.out.println("First: " + first);
System.out.println("Second: " + second);
}
}Output:
First: 20 Second: 10
Explanation
We use addition and subtraction or bitwise XOR to swap without extra memory.
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler