Java Program To Swap Two Number

Swapping two variables is a fundamental logic exercise that every developer encounters early in their journey. Whether you are reordering elements in a list or implementing a sorting algorithm like Bubble Sort, understanding how to exchange values between two memory locations is essential.

In Java, because we typically work with primitive types like int, swapping requires a specific logical flow to ensure no data is lost during the transition. Here is the most common and readable way to achieve this using a temporary variable.

public class SwapNumbers {
    public static void main(String[] args) {
        // Step 1: Initialize two integer variables
        int a = 5;
        int b = 10;

        System.out.println("--- Before Swapping ---");
        System.out.println("Value of a: " + a);
        System.out.println("Value of b: " + b);

        // Step 2: Perform the swap using a third (temporary) variable
        // Imagine 'temp' as a placeholder to prevent 'a' from being overwritten
        int temp = a; // temp now holds 5
        a = b;        // a now holds 10
        b = temp;     // b now holds 5

        System.out.println("\n--- After Swapping ---");
        System.out.println("Value of a: " + a);
        System.out.println("Value of b: " + b);
    }
}
Developer Tip: Use descriptive variable names even in simple exercises. While a and b are fine for tutorials, in a real application, you might use currentPrice and previousPrice to make the code self-documenting.

How the Logic Works

If you try to swap values by simply writing a = b; b = a;, you will find that both variables end up with the same value. This happens because the moment you assign b to a, the original value of a is overwritten and lost forever.

To visualize this, imagine you have a Glass of Orange Juice (A) and a Glass of Apple Juice (B). If you want to put the Apple Juice into Glass A, you first have to pour the Orange Juice into an Empty Third Glass (Temp). Once Glass A is empty, you can move the Apple Juice over, and finally, pour the Orange Juice from the Third Glass into Glass B.

Common Mistake: Forgetting to assign the value back from the temporary variable. Beginners often write temp = a; a = b; but then forget to finish the process with b = temp;, leaving the second variable unchanged.

Swapping Without a Temporary Variable

While the temporary variable method is the most readable and "standard" way to swap, you might encounter scenarios in interviews where you are asked to swap numbers without using a third variable. This can be done using simple arithmetic:

// Arithmetic Swap Logic
a = a + b; // a becomes 15 (5 + 10)
b = a - b; // b becomes 5 (15 - 10)
a = a - b; // a becomes 10 (15 - 5)
Watch Out: Be careful with the arithmetic swap method when dealing with very large numbers. If the sum of a + b exceeds Integer.MAX_VALUE (2,147,483,647), it will cause an integer overflow, potentially leading to incorrect results.

Practical Real-World Example

In software development, swapping is rarely done in isolation. A classic example is the Selection Sort algorithm. When the algorithm finds the smallest number in an array, it must "swap" it with the element currently at the front of the list. Without the logic shown above, the algorithm would accidentally delete data instead of reordering it.

Best Practice: Always prefer the Temporary Variable method for production code. It is easier to read, easier to debug, and avoids the mathematical pitfalls of overflow or floating-point precision issues.

By mastering this simple three-step process, you have learned how to safely manipulate data in memory—a skill that will serve you throughout your entire career as a Java developer.