Java program to swap two numbers

Let’s learn java program to swap two numbers.

Java program to swap two numbers

Swap two numbers in java is one of the frequently asked interview question.

Also read – java String toCharArray() method

Well, there are few ways to swap two numbers in java,

  1. swap two numbers with temporary variable
  2. swap two numbers without temporary variable

swap two numbers with temporary variable

Let’s learn swapping two numbers using a temporary variable. Here’s program to swap two numbers,

import java.util.Scanner;

public class SwapTwoNumbersInJava
{
   public static void main(String[] args)
   {
      int a;
      int b;
      int swap;
      System.out.println("Please enter two integers to swap : ");
      Scanner sc = new Scanner(System.in);
      a = sc.nextInt();
      b = sc.nextInt();
      System.out.println("Before swap : a = " + a + "\nBefore swap : b = " + b);
      swap = a;
      a = b;
      b = swap;
      System.out.println("After swap : a = " + a + "\nAfter swap : b = " + b);
   }
}



Output:

java program to swap two numbers

swap two numbers without temporary variable

First let’s learn algorithm for swapping of two numbers without using third variable,

Also read – swap two numbers in java using function

  • read values of two numbers number1 and number 2.
  • then add number1 and number2 and assign value to number1. That is, number1 = number1 + number2.
  • In the next step subtract number1 and number2 and assign value to number2. That is, number2 = number1 – number2.
  • now subtract number1 and number2 and assign value to number1. That is, number1 = number1 – number2.
  • lastly print value of number1 and number2.

Here let’s learn swapping program in java without using third variable. Here’s program to swap two numbers without using third variable,

// how to swap two numbers without using a temporary variable

import java.util.Scanner;

public class SwapTwoNumbers
{
   public static void main(String[] args)
   {
      int a;
      int b; 
      System.out.println("Please enter two integers to swap : ");
      Scanner sc = new Scanner(System.in);
      a = sc.nextInt();
      b = sc.nextInt();
      System.out.println("Before swap : a = " + a + "\nBefore swap : b = " + b);
      a = a + b;
      b = a - b;
      a = a - b;
      System.out.println("After swap : a = " + a + "\nAfter swap : b = " + b);
   }
}



Output:

Please enter two integers to swap : 10 5
Before swap : a = 10
Before swap : b = 5
After swap : a = 5
After swap : b = 10