Let’s learn java program to swap two numbers.
Java program to swap two numbers
Let’s learn two ways to swap two numbers in java.
Using temporary variable
To swap two numbers in java using temporary variable first user enters two numbers which is stored in two integer variables a and b using nextInt() method of Scanner class.
In the next step print the values of variables a and b before swapping on the console. Now store variable a value in integer variable swap and variable b value in variable a.
Finally variable swap value is stored in variable b. Now let’s see java program to swap two numbers using temporary variable.
import java.util.Scanner; public class SwapTwoNumbersInJava { public static void main(String[] args) { int a; int b; int swap; System.out.println("Please enter two integers to swap : "); Scanner sc = new Scanner(System.in); a = sc.nextInt(); b = sc.nextInt(); System.out.println("Before swap : a = " + a + "\n Before swap : b = " + b); swap = a; a = b; b = swap; System.out.println("After swap : a = " + a + "\n After swap : b = " + b); } }
Output:

Swap two numbers without using temporary variable
Here’s the algorithm to swap two numbers in java without using temporary variable.
- First user inputs two numbers which is stored in two integer variables a and b using nextInt() method of Scanner class.
- Print the values of variables a and b before swapping.
- Then add values of variable a and b and assign this value to variable a. That is, a = a + b.
- In the next step subtract values of variable a and b and assign this value to variable b. That is, b = a – b.
- Now subtract values of variable a and b and assign value to variable a. That is, a = a – b.
- Lastly print values of variable a and b.
Here’s java program to swap two numbers without using temporary variable.
import java.util.Scanner; public class SwapTwoNumbers { public static void main(String[] args) { int a; int b; System.out.println("Please enter two integers to swap: "); Scanner sc = new Scanner(System.in); a = sc.nextInt(); b = sc.nextInt(); System.out.println("Before swap: a = " + a + "\n Before swap: b = " + b); a = a + b; b = a - b; a = a - b; System.out.println("After swap: a = " + a + "\n After swap: b = " + b); } }
Output:
Please enter two integers to swap: 10 5
Before swap: a = 10
Before swap: b = 5
After swap: a = 5
After swap: b = 10