Swapping numbers

Swapping numbers means exchanging the values between two or more variables. In this program we are going to swap two numbers without using any temporary variable.

Logic

  1. Store addition of variable a and b (a+b) to variable a.
  2. Now extract b from a and store it to b.
  3. Extract b from a and store it to a.

Now b is holding a’s original value and similarly a is holding b’s original value.

Program

import java.util.Scanner;

public class SwapWithoutTemp {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter number a : ");
        int a = scanner.nextInt();

        System.out.println("Enter number b : ");
        int b = scanner.nextInt();

        System.out.println("Before swapping a = " + a + " b = " + b);

        //Swapping number
        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("After swapping a = " + a + " b = " + b);

    }

}

Output

Enter number a : 10
Enter number b : 200
Before swapping a = 10 b = 200
After swapping a = 200 b = 10