Swapping Two Numbers in Java

Swapping two numbers is one of the fundamental concepts that every programmer should know. Whether you’re a beginner or an experienced developer, it’s essential to understand multiple ways to swap two numbers in Java. In this Post, we will cover 5 different methods of Java Program to swap two numbers.

Let’s dive in and explore these techniques step by step!

1. Swapping Two Numbers Using a Temporary Variable

So, the first method is the easiest and most common one—using a temporary variable. We bring in a new third variable to hold one of the numbers while we swap.

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5, b = 10;
        int temp;

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

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

Explanation:

  • We have two variables, a = 5 and b = 10.
  • We create a third variable, temp, and set temp = a (so temp holds the value of a).
  • Then, we assign the value of b to a, so now a = 10.
  • Finally, we assign temp (which is 5) to b, making b = 5.

2. Swapping Two Numbers Without Using a Temporary Variable (Arithmetic Operations)

You can swap two numbers without using any additional variables by utilizing basic arithmetic operations: addition and subtraction.

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5, b = 10;

        a = a + b;
        b = a - b;
        a = a - b;

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

Explanation:

  • First, we add the values of a and b together and store the result in a. So, a = a + b.
  • next, we subtract b from the new a and assign the result to b. Now, b holds the original value of a.
  • Finally, we subtract b from the new a to get a = a – b, which gives us the original value of b.

3. Swapping Two Numbers Using Multiplication and Division

Now let’s try something similar, but this time using multiplication and division instead of adding and subtracting

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5, b = 10;

        a = a * b;
        b = a / b;
        a = a / b;

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

Explanation:

  • First, we multiply a and b together and store the result in a. So, a = a * b.
  • Then, we divide new a by b and assign the result to b. Now b holds the original value of a.
  • Finally, we divide the new a by the new b to get the original value of b.
Note :- Keep in mind that this method works great, but Be careful while using this method, —if one of the numbers is Zero it can give arithmetic exception since you can’t divide by zero.

4. Swapping Two Numbers Using a Single Statement

Here’s a cool way to swap two numbers using a single statement. This is more of a tricky hack, often used in interviews to test logical reasoning.

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5, b = 10;

        b = a + b - (a = b);

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

Explanation:

This is a compact way to swap values without using extra variables or separate lines of code. The expression swaps a and b in a single statement by updating both variables simultaneously. While it’s efficient, readability might suffer, so use this approach with caution.


5. Swapping Two Numbers Using a Function

Finally, let’s look at how we can swap numbers by using a function. This is a good approach when you want to reuse the swapping logic in multiple places in your program.

Here’s how you can write a function that swaps two numbers:

public static int[] swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    return new int[] {a, b};
}

Now, you just call the swap() function and pass in the two numbers you want to swap. It returns an array containing the swapped values.

Here’s how you would use it in your main method:

int a = 5, b = 10;
int[] swapped = swap(a, b);
System.out.println("After swap: a = " + swapped[0] + ", b = " + swapped[1]);

This approach makes your code more modular, and it’s helpful when you want to swap numbers multiple times throughout your program.


Conclusion

In this blog, we explored 5 different ways to swap two numbers in Java, ranging from the traditional approach using a temporary variable to more advanced techniques like the XOR operator and single-line swaps. Each method has its own pros and cons, so understanding them will help you choose the best approach for your use case.

Stay tuned for more Java programming tutorials and tips to improve your coding skills! Happy Journey!

Follow Along on YouTube!

If you enjoyed this tutorial and want to dive deeper into Java programming, testing concepts, and practical coding solutions, check out my YouTube channel Testers Journey! I cover a wide range of topics to help you sharpen your skills, whether you’re just starting out or looking to advance in your testing career.

Don’t forget to subscribe to join the journey and stay updated with my latest tutorials and tips. Let’s make learning Java fun and easy, one step at a time!

Add a Comment

Your email address will not be published. Required fields are marked *