Java Program to Swap 2 Numbers Without Using 3rd Variable

In this program we will write a Java program Perform Swapping of 2 numbers without using 3rd Variable. We will swap values of 2 Integer variables without using a 3rd Temporary Variable.

Java program to swap two numbers without 3rd variable –
import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
      // Code to swap 'x' and 'y'
      x = x + y;  // x now becomes 15
      y = x - y;  // y becomes 10
      x = x - y;  // x becomes 5
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}
Output
Enter x and y
4 5
Before Swapping
x = 4
y = 5
After Swapping
x = 5
y = 4
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *