Java swap

Hello everyone!! Welcome to flower brackets blog. Today we will discuss java swap.

java swap

In this post let’s see java program to swap two numbers. Well, there are two ways to swap 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 swapping using temporary or third 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 :

java swap


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