Best Way In Java To Swap Two Numbers

Hello everyone!! Welcome to flower brackets blog. Today we will discuss best way in java to swap two numbers.

Also Read – Add Two Numbers With Bitwise Operator

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

  1. with temporary variable
  2. without temporary variable

Example: Best Way In Java To Swap Two Numbers

/* WITH TEMPORARY VARIABLE */

import java.util.Scanner;

public class SwapTwoNumbers
{
   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:

Best Way In Java To Swap Two Numbers


/* 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

You May Also Like