Java program to swap two numbers

Today we will learn java program to swap two numbers.

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

Also read – write a java program to swap two numbers using bitwise operators

  1. with temporary variable
  2. without temporary variable

Let’s see how to swap two numbers using temporary or third variable,

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


// let's see swapping without 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


Also read – swap two numbers in java using function

Related Posts