Java Programs

Swap two number without using third Variable

We will see a Java program to swap two numbers without using a temporary variable.

This is also an important program that is often asked in the interview.

In the swap operation, we basically change the value of a variable.

Suppose the assigned value of the variable ‘a’ is 5 and the variable b has the value 4.

After the swap, ‘a’ will have the value 4 and ‘b’ will have the value 5.

How will this Java program behave?

Our Java program will take two values as input. And after performing the swap, it will print the output.

For example: a=5 and b=4

Now after execution of the program our output will be 

a=4 and b = 5

Program:

import java.util.Scanner;

public class Main {

	public static void main(String ...args){
        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 firstno : "+firstno+" secondno and "+secondno);
        
        firstno=firstno-secondno;
	    secondno=firstno+secondno;
	    firstno=secondno-firstno;
	    System.out.print("nafter swapping firstno : "+firstno+" secondno and "+secondno);
    }

}

Output:

Enter first number- 4
Enter second number- 5
before swapping firstno : 4 secondno and 5nafter swapping firstno : 5 secondno and 4

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs