Java – Swapping two numbers using temporary variable

In this article, we will discuss one of the famous interview question on how to swap two numbers using third or temporary variable

Actually, there are n number of ways to achieve swap program but here we will focus on swapping 2 numbers using third or temporary variable

Swapping 2 numbers :

  • Initially there are 2 numbers firstNum and secondNum and we are interested to swap these 2 numbers
  • Declare third variable called iTempVar
  • Now for swapping,
    • 1st assign firstNum value into iTempVar
    • 2nd assign secondNum value into firstNum
    • Finally, assign iTempVar into firstNum
  • This way we will achieve in swapping 2 numbers

Swap2NumbersUsingThirdVariable.java

package in.bench.resources.swap.numbers;

public class Swap2NumbersUsingThirdVariable {

	public static void main(String[] args) {

		int firstNum = 33;
		int secondNum = 66;
		int iTempVar;

		// original values before swap
		System.out.println("Before swap of 2 numbers :");
		System.out.println("First Number  : " + firstNum);
		System.out.println("Second Number : " + secondNum);


		// swapping 2 numbers using third/temporary variable
		iTempVar = firstNum; // 1n=33, 2n=66, tn=33
		firstNum = secondNum; // 1n=66, 2n=66, tn=33
		secondNum = iTempVar; // 1n=66, 2n=33, tn=33


		// original values before swap
		System.out.println("\nAfter swap of 2 numbers :");
		System.out.println("First Number  : " + firstNum);
		System.out.println("Second Number : " + secondNum);
	}
}

Output:

Before swap of 2 numbers :
First Number  : 33
Second Number : 66

After swap of 2 numbers :
First Number  : 66
Second Number : 33

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles :

Happy Coding !!
Happy Learning !!

Java 8 - Check whether number is Positive or Negative or Zero ?
Java - Check whether the given number is Armstrong number or Not