Java Programs

Swap two number using third Variable

We will learn swapping two numbers using a third variable in the Java programming language.

This is also a very important program that is often asked in job interviews.

Before we start writing the program directly, let us understand what we want to achieve with this program.

Basically, swapping numbers means

Suppose variable a has been assigned the value 2 and variable b has been assigned the value 4, then in the swap operation we will swap the value and assign the value of a, i.e. 2, to b and the value of b, i.e. 4, to variable a.

How will our program behave?

As we have already seen above, we have to achieve this in the program.

In the swap program without a third variable, we will assign two different values to the different variables.

For example: a=2 and b=4

After running the program, our output should now look like this

a=4 and b = 2

Program

import java.util.Scanner;

public class Main {

	  public static void main(String ...args){
        int tempvar;
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter first number- ");  
        int firstno= sc.nextInt();  
        System.out.print("Enter second number- ");  
        int secondno= sc.nextInt();  
        System.out.print("before swapping number are : "+firstno+" and "+secondno);  
        tempvar=firstno;
	    firstno=secondno;
	    secondno=tempvar;
	    System.out.print("nafter swapping number are : "+firstno+" and "+secondno);
	 }

}

Output:

Enter first number- 5
Enter second number- 6
before swapping number are : 5 and 6nafter swapping number are : 6 and 5

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs