Swap two number in java without using the 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.

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

Java Program to swap two number without using third variable

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.print("before swapping firstno : "+firstno+" secondno and "+secondno);  
	    System.out.print("\nafter swapping firstno : "+firstno+" secondno and "+secondno);


Java program to swap two number