You are here

Swapping of two numbers in Java

Java program to swap two numbers with and without using an extra variable. Swapping is frequently used in sorting techniques such as bubble sort, quick sort, and other algorithms.

Swapping program in Java

import java.util.Scanner;

class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y, t;
      System.out.println("Enter two numbers (x & y)");
      Scanner in = new Scanner(System.in);
     
      x = in.nextInt();
      y = in.nextInt();
     
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
     
      t = x;
      x = y;
      y = t;
     
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

Output of program:
Java program to swap numbers output
Swap numbers program class file.

Swapping without an extra 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);
 
      x = x + y;
      y = x - y;
      x = x - y;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

For other methods to swap numbers see: C program to swap using bitwise XOR.