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 – java string toCharArray() method

  1. with temporary variable
  2. without temporary variable

Let’s see java program to swapping two numbers using a temporary 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


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


Also read – java remove character from string