Swap Two Numbers Without a Third Variable in Java

By Swap Two Numbers Without a Third Variable in Java

Swapping numbers will be helpful when creating large Java programs. Swapping is frequently used in sorting algorithms such as bubble sort, quick sort, etc.

Swapping is the act of exchanging values of variables. In this article, I am going to teach you how to swap two numbers without using a third (temp) variable.

Swap using multiplication and division

public class Swap {
    public static void main(String arg[]) {
        System.out.println("Before swapping");
        int x = 3;
        int y = 5;
        System.out.println("value of x:" + x);
        System.out.println("value of y:" + y);
        System.out.println("\nAfter swapping");
        x = x * y;
        y = x / y;
        x = x / y;
        
        System.out.println("value of x:" + x);
        System.out.println("value of y:" + y);
    }
}

The following is the output of our code

run:
Before swapping
value of x:3
value of y:5
After swapping
value of x:5
value of y:3

Swap using Bitwise operators

public class Swap {
    public static void main(String arg[]) {
        System.out.println("Before swapping");
        int x = 3;
        int y = 5;
        System.out.println("value of x:" + x);
        System.out.println("value of y:" + y);
        System.out.println("\nAfter swapping");
        x = x ^ y;
        y = x ^ y;
        x = x ^ y;
        
        System.out.println("value of x:" + x);
        System.out.println("value of y:" + y);
    }
}

The following is the output of our code

run:
Before swapping
value of x:3
value of y:5
After swapping
value of x:5
value of y:3

Conclusion

Congratulations folks! In this article, you learned how to swap two numbers without a third variable in Java.

Thank you for reading. Please share with your friends with links below. See you in the next post.

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.