Java Program to Swap two number without using third Variable

In this tutorial you will see Java program to swap two number without using temp variable.

This is also a important program which commonly asked in interview.

Read This: C program to swap two number without using third variable.

In Swapping operation basically we change value of variable.

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

After Swapping of it, ‘a’ will have 4 and value ‘b’ will have 5.

How this java program will behave?

Our Java program will take two value as an input. And after performing swapping operation it will print output.

For example: a=5 and b=4

Now after execution of the program our output will be 

a=4 and b = 5

Program 1: Swap two number without using third variable in Java

import java.util.*;  
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.println("Before swapping first no : "+firstno+" second no and "+secondno);  
        firstno=firstno-secondno;
	    secondno=firstno+secondno;
	    firstno=secondno-firstno;
	    System.out.println("After swapping first no : "+firstno+" second no and "+secondno);
    }
}

Output:

Enter first number- 34
Enter second number- 55
Before swapping first no : 34 second no and 55
After swapping first no : 55 second no and 34

Conclusion


In this tutorial we have gone through the Java program to swap two numbers without using a temporary variable. Swapping is a fundamental operation in programming, and this particular method is often a common interview question. Here the concept is, exchanging the values of two variables without taking any third variable.

With the basic arithmetic operations, we have swapped values of the two variables. The program prompted the user to input two numbers, demonstrated the state of the variables before swapping, and then showcased the result after the swapping operation.

In the example provided, the program successfully swapped the values of ‘a’ and ‘b’, transforming them from 34 and 55 to 55 and 34, respectively.

Hope the above program helped you to understand swapping of two numbers without using third variable in java.

Happy Coding !!