Swapping Two Numbers Without a Third Variable: A Simple Trick

kavindulakmal

Kavindu Lakmal Wickramasinghe

Posted on April 17, 2024

Swapping Two Numbers Without a Third Variable: A Simple Trick

Swapping two numbers is a common task in programming, often used in algorithms and various applications. While the traditional approach involves using a temporary variable to store one of the numbers during the swap, there's an elegant trick in Java to accomplish this without the need for a third variable. In this blog post, we'll explore this efficient technique and implement it in a Java program. By understanding this method, you'll not only save memory but also gain insight into the inner workings of Java's assignment operators. Let's dive in and discover how to perform number swapping without the overhead of an additional variable.

package testing_code;

import java.util.Scanner;

public class SwapNumbers {

    public static void swapNumbersWithoutVariable(int n1,int n2) {
        System.out.println("Before Swapping");
        System.out.println("First number" +n1);
        System.out.println("Second number "+n2);

        n1= n1+n2;
        n2= n1-n2;
        n1= n1-n2;

        System.out.println("After Swapping");
        System.out.println("First number " +n1);
        System.out.println("Second number "+n2);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number for number 1 ");
        int n1 = scanner.nextInt();

        System.out.println("Enter a number for numner 2 ");
        int n2 = scanner.nextInt();

        swapNumbersWithoutVariable(n1, n2);

        scanner.close();

    }

}
Enter fullscreen mode Exit fullscreen mode

In this blog post, we explored a clever technique to swap two numbers without using a third variable in Java. Traditionally, swapping involves the use of a temporary variable to store one of the values during the swap operation. However, by leveraging the properties of arithmetic and bitwise operators in Java, we can achieve the same result more efficiently. This approach not only saves memory but also offers insight into the nuances of Java's assignment operators. By understanding this technique, programmers can optimize their code and enhance their problem-solving skills. Join us as we delve into the intricacies of number swapping in Java and uncover the simplicity behind this elegant solution.

Thank you for taking the time to read this post, and I hope you found this exploration both enlightening and practical. Happy coding!
© KAVINDU™ | 2024

💖 💪 🙅 🚩
kavindulakmal
Kavindu Lakmal Wickramasinghe

Posted on April 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related