Java Program to Swap Two Numbers

Updated on September 30, 2024
Swap Two Numbers header image

Introduction

Swapping two numbers in programming involves exchanging the values of two variables. In Java, this task can be accomplished in several ways, each with its own unique approach and use case. Understanding these methods is crucial for efficient data manipulation and forms a fundamental part of algorithm design.

In this article, you will learn how to swap two numbers in Java using different techniques. Explore examples that demonstrate the use of temporary variables, arithmetic operations, and bitwise XOR operation to achieve this task effectively.

Swapping Using a Temporary Variable

Basic Swap with Temporary Storage

  1. Declare and initialize two integer variables.

  2. Use a third temporary variable to facilitate the swap.

    java
    int a = 5;
    int b = 10;
    int temp;
    
    temp = a; // Store the value of 'a' in 'temp'
    a = b;    // Assign the value of 'b' to 'a'
    b = temp; // Assign the value stored in 'temp' to 'b'
    

    This code block initializes variables a and b with values 5 and 10, respectively. The variable temp is used to hold the value of a temporarily while a is set to the value of b, and finally, b is set to the original value of a stored in temp.

Swapping Without Using a Temporary Variable

Arithmetic Operations

  1. Use addition and subtraction to swap values without a temporary variable.

    java
    int a = 5;
    int b = 10;
    
    a = a + b; // a becomes 15
    b = a - b; // b becomes 5 (15 - 10)
    a = a - b; // a becomes 10 (15 - 5)
    

    Here, the numbers are swapped using addition and subtraction. Initially, a is updated to be the sum of both numbers. Then, b is recalculated by subtracting the new value of a minus the old b, and finally, a is updated by subtracting the new b.

Bitwise XOR Operation

  1. Apply the Bitwise XOR operation for an efficient swap without any extra space.

    java
    int a = 5;
    int b = 10;
    
    a = a ^ b; // XOR a and b, and store it in a
    b = a ^ b; // Now b is the value of original a
    a = a ^ b; // Now a is the value of original b
    

    The XOR operation is an efficient bitwise technique to swap variables without a third variable. The process involves transforming the values into a series of bits and using XOR to switch these bits between the two variables without any additional storage.

Conclusion

Swapping two numbers in Java can be achieved through multiple methods depending on the scenario and performance needs. Whether using a temporary variable, arithmetic manipulations, or a bitwise XOR, each approach offers unique advantages. Mastering these techniques not only aids in fundamental programming tasks but also enhances understanding of how data can be manipulated efficiently within memory. Use these methods appropriately to keep your code clean and optimal.