In this post, we’ll look at how to write a java program to swap two numbers using third variable. The java program will swap the two given integer numbers using a local variable as a temporary variable. The reassigning variables are used to swap two numbers. The third variable is used as a buffer to hold a value while the values are swapped.

Swap two numbers in java

The following are the steps for swapping two numbers:

  1. Assign a to a temp variable   temp = a
  2. Assign b to a                          a = b
  3. Assign temp to b                    b = temp

Let’s look at number swapping with an example.

a = 4 ; b = 7 ;
a = 4 ; b = 7 ; temp = 0;  -- Introducing temp variable
a = 4 ; b = 7 ; temp = 4;  -- temp = a
a = 7 ; b = 7 ; temp = 4;  -- a= b
a = 7 ; b = 4 ; temp = 4;  -- b= temp

Java Program

package in.yawin;

public class SwapTwoNumbers {
	public static void main(String[] args) {
		int a = 4;
		int b = 7;
		System.out.println("Before Swapping 2 Numbers");
		System.out.println("Number 1 is " + a);
		System.out.println("Number 2 is " + b);
		int tmp = 0;

		tmp = a;
		a = b;
		b = tmp;

		System.out.println("After Swapping 2 Numbers");
		System.out.println("Number 1 is " + a);
		System.out.println("Number 2 is " + b);
	}
}

Output

Before Swapping 2 Numbers
Number 1 is 4
Number 2 is 7

After Swapping 2 Numbers
Number 1 is 7
Number 2 is 4

Explanation

The java programme will make use of two numbers that are stored in two variables. In the two variables, the two numbers are swapped. To swap the values of these two variables, a temporary variable is used. The first value is saved in the temporary variable. The second number is then saved in the first variable. The second value will be stored in the first variable. The value of the temporary variable will now be assigned to the second variable. The first value will now be assigned to the second variable. In this manner, two given numbers can be swapped using a temporary variable in a Java programme.

Leave a Reply