Java – Swap Two Variables Without a Temp Variable

Swapping two variables is a common task in programming. Traditionally, we use a temporary variable to hold one value while swapping, but Java allows us to swap two variables without using a temp variable.

In this tutorial, we will explore different ways to achieve this in Java with real-world examples.

Table of contents:

P.S Tested with Java 21

1. Swapping Using Arithmetic Operators

We can swap two numbers using addition (+) and subtraction (-).

SwapWithoutTemp.java

package com.mkyong;

public class SwapWithoutTemp {

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

        System.out.println("Before Swap: a = " + a + ", b = " + b);

        // Swap using arithmetic operations
        a = a + b;
        b = a - b;
        a = a - b;

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

}

Output:


Before Swap: a = 10, b = 20  
After Swap: a = 20, b = 10  

Explanation:

  1. a = a + b;a now holds the sum of a and b (10 + 20 = 30).
  2. b = a - b;b now gets the original value of a (30 - 20 = 10).
  3. a = a - b;a now gets the original value of b (30 - 10 = 20).

Note:

This method may cause an integer overflow if a + b exceeds the maximum value for integers (Integer.MAX_VALUE).

2. Swapping Using Multiplication and Division

Another alternative is to use multiplication (*) and division (/), but it only works if neither a nor b is zero.

SwapUsingMultiplication.java

package com.mkyong;

public class SwapUsingMultiplication {

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

        System.out.println("Before Swap: a = " + a + ", b = " + b);

        // Swap using multiplication and division
        a = a * b;
        b = a / b;
        a = a / b;

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

}

Explanation:

  1. a = a * b;a holds the product of a and b.
  2. b = a / b;b gets the original value of a.
  3. a = a / b;a gets the original value of b.

Output:


Before Swap: a = 10, b = 20
After Swap: a = 20, b = 10

Limitations:

  • This method does not work if either a or b is zero.
  • It may cause overflow with large numbers.

3. Swapping Using Bitwise XOR Operator

The XOR bitwise operator (^) is an efficient way to swap two variables without using extra space.

SwapUsingXOR.java

package com.mkyong;

public class SwapUsingXOR {

    public static void main(String[] args) {
        
        int x = 10, y = 20;

        System.out.println("Before Swap: x = " + x + ", y = " + y);

        // Swap using XOR
        x = x ^ y;
        y = x ^ y;
        x = x ^ y;

        System.out.println("After Swap: x = " + x + ", y = " + y);

    }
}

Output:


Before Swap: x = 10, y = 20
After Swap: x = 20, y = 10

Explanation:

  1. x = x ^ y;x now holds the XOR result of x and y.
  2. y = x ^ y;y gets the original value of x.
  3. x = x ^ y;x gets the original value of y.

Why Use XOR?

  • This method works well with integer values.
  • It does not suffer from integer overflow issues like the arithmetic method.
  • However, it may not be as readable as the addition-subtraction method.

4. Understanding XOR (^) Operator in Java for Swapping Two Variables

The bitwise XOR (^) operator is a powerful tool in Java that allows us to manipulate individual bits of integers. It is commonly used in programming for tasks like encryption, error detection, and variable swapping.

What is XOR (^) Operator?

The XOR (exclusive OR) operator compares each bit of two numbers. It returns 1 if the bits are different and 0 if they are the same.

XOR Truth Table

A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Example: XOR of Two Numbers

Let’s take two numbers:
5 (0101 in binary) and 8 (1000 in binary)

Bit Position 5 (0101) 8 (1000) 5 ^ 8
1st bit 1 0 1
2nd bit 0 0 0
3rd bit 1 0 1
4th bit 0 1 1

Result:


  5  =  0101
  8  =  1000
----------------
5 ^ 8 =  1101 (which is 13 in decimal)

How XOR Works for Swapping Two Numbers

The XOR operator has a special property:

  • If we apply XOR twice with the same number, the original value is restored.

That is:


X ^ Y ^ Y = X

This property allows us to swap two numbers without using a temporary variable.

Swapping Two Numbers Using XOR

Let’s break down the swap step by step:

SwapUsingXOR.java

package com.mkyong;

public class SwapUsingXOR {
    
    public static void main(String[] args) {
        int x = 5, y = 8;

        System.out.println("Before Swap: x = " + x + ", y = " + y);

        // Step 1: XOR both numbers and store result in x
        x = x ^ y; // x now holds (5 ^ 8) = 13

        // Step 2: XOR x with y and store result in y
        y = x ^ y; // y now holds (13 ^ 8) = 5 (original value of x)

        // Step 3: XOR x with new y and store result in x
        x = x ^ y; // x now holds (13 ^ 5) = 8 (original value of y)

        System.out.println("After Swap: x = " + x + ", y = " + y);
    }
}

Step-by-Step Explanation of XOR Swap

Let’s assume x = 5 (0101 in binary) and y = 8 (1000 in binary).

Step 1: Compute x = x ^ y


  5  =  0101
  8  =  1000
----------------
x = 5 ^ 8 = 1101 (which is 13 in decimal)

Now, x = 13 and y = 8.

Step 2: Compute y = x ^ y


 13  =  1101
  8   =  1000
----------------
y = 13 ^ 8 = 0101 (which is 5 in decimal)

Now, x = 13 and y = 5 (original x value is now in y).

Step 3: Compute x = x ^ y


 13  =  1101
  5   =  0101
----------------
x = 13 ^ 5 = 1000 (which is 8 in decimal)

Now, x = 8 and y = 5. Swap is complete! 🎉

Advantages of Using XOR for Swapping

No extra memory needed – We don’t use a temporary variable.
Works for all integers – Unlike arithmetic methods, there’s no risk of integer overflow.
Efficient bitwise operation – XOR is a low-level operation and works efficiently in hardware.

Disadvantages of XOR Swap

Less readable – XOR swap is not as intuitive as using a temp variable.
Doesn’t work well with floating-point numbers – Works only with integers.
Hard to debug – If not careful, mistakes can be hard to trace.

Which Method Should You Use?

Method Pros Cons
Addition/Subtraction Simple and easy to understand Risk of integer overflow
Bitwise XOR No risk of overflow, works well with integers Less readable
Multiplication/Division Works well with non-zero values Cannot handle zeros, risk of overflow

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments