Java Program to Swap Two Numbers

Swapping two numbers is a classic beginner programming problem. It helps learners understand variables, memory handling, and basic logic building in Java.

In this tutorial, we will create a Java program to swap two numbers using both a temporary variable and a simple arithmetic method.

By the end of this guide, you will understand multiple ways to swap values in Java efficiently.

Concept Overview

Swapping means exchanging the values of two variables. For example, if a = 5 and b = 10, after swapping, a = 10 and b = 5.

We can achieve this using a temporary variable or using arithmetic operations like addition and subtraction.

Program (Using Temporary Variable)

Java
import java.util.Scanner;

public class SwapNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int a = sc.nextInt();

        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping:");
        System.out.println("First number: " + a);
        System.out.println("Second number: " + b);
    }
}

Output

TEXT
Enter first number: 5
Enter second number: 10
After swapping:
First number: 10
Second number: 5

Detailed Explanation

The program takes two input numbers from the user using the Scanner class.

A temporary variable is used to store the value of the first number.

Then the value of the second number is assigned to the first number.

Finally, the stored value in the temporary variable is assigned to the second number.

Program (Without Temporary Variable)

Java
int a = 5, b = 10;

// Swap without temp
 a = a + b;
 b = a - b;
 a = a - b;

Example Walkthrough

Let us consider a = 5 and b = 10.

After swapping using a temporary variable or arithmetic method, the values become a = 10 and b = 5.

Applications

Swapping is used in sorting algorithms like bubble sort, selection sort, and insertion sort.

It is also used in memory management and data manipulation tasks.

Advantages of This Approach

This program helps beginners understand variable assignment and data manipulation.

It demonstrates multiple ways to solve the same problem.

Limitations

The arithmetic method may cause overflow for large numbers.

Improvements You Can Make

You can implement swapping using bitwise XOR for better efficiency.

You can also create a method to reuse swapping logic.

This Java program helps build strong logical thinking and understanding of variable manipulation.