You are here

Java program to swap two numbers

Java program to swap two numbers using a temporary variable. To swap numbers without using extra variable see another code below. Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc..

Swapping using temporary or third variable

  1. import java.util.Scanner;
  2.  
  3. class SwapNumbers
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int x, y, temp;
  8.       System.out.println("Enter x and y");
  9.       Scanner in = new Scanner(System.in);
  10.      
  11.       x = in.nextInt();
  12.       y = in.nextInt();
  13.      
  14.       System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
  15.      
  16.       temp = x;
  17.       x = y;
  18.       y = temp;
  19.      
  20.       System.out.println("After Swapping\nx = "+x+"\ny = "+y);
  21.    }
  22. }

Output of program:
Java program to swap numbers outputSwap numbers program class file.

Swapping without temporary variable

  1. import java.util.Scanner;
  2.  
  3. class SwapNumbers
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int x, y;
  8.       System.out.println("Enter x and y");
  9.       Scanner in = new Scanner(System.in);
  10.  
  11.       x = in.nextInt();
  12.       y = in.nextInt();
  13.  
  14.       System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
  15.  
  16.       x = x + y;
  17.       y = x - y;
  18.       x = x - y;
  19.  
  20.       System.out.println("After Swapping\nx = "+x+"\ny = "+y);
  21.    }
  22. }

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