Without using the third variable, swapping the two numbers can be done by using IF/ELSE statement. Just proper condition needs to be mentioned. Here only the IF/ELSE statement are important.

Program:

import java.util.Scanner;
public class Swapping
{
   public static void main(String[] args)
   {
     Scanner in = new Scanner(System.in);
     System.out.print("Enter the first number: ");
     int n1 = in.nextInt();
     System.out.print("Enter the second number: ");
     int n2 = in.nextInt();
 
     System.out.println("Before swapping value of first number: "+n1+" and second number: "+n2);
     if(n1<n2)
     {
       n1=n1+n2;
       n2=n1-n2;
       n1=n1-n2;
     }
     else
     {
       n2=n2+n1;
       n1=n2-n1;
       n2=n2-n1;
     }
     System.out.println("After swapping value of first number: "+n1+" and second number: "+n2);
   }
}

Output:

Enter the first number: 32
Enter the second number: 52
Before swapping value of first number: 32 and second number: 52
After swapping value of first number: 52 and second number: 32

You can download the pdf file of the Swapping.

Advertisements