Introduction

Swapping two numbers is one of the most common beginner programs in Java. Although it looks like a simple three-line exercise, it introduces an important programming concept—exchanging values without losing data.

This logic appears in many real-world algorithms such as Bubble Sort, Selection Sort, Quick Sort, and other data manipulation techniques. Learning different ways to swap values also helps you understand variable assignment, arithmetic operations, and bitwise operators.

In this tutorial, you'll learn four different techniques to swap two numbers in Java, understand how each method works internally, compare their advantages and disadvantages, and explore common interview questions related to swapping numbers.

Advertisement

What Does Swapping Mean in Programming?

Swapping means exchanging the values stored in two variables.

For example:

Before swapping:

a = 10
b = 20

After swapping:

a = 20
b = 10

You cannot simply write:

a = b;
b = a;

because the first statement overwrites the original value of a. Once it's lost, it cannot be recovered. That's why we either use a temporary variable or apply mathematical or bitwise techniques.


Method 1: Swap Using a Temporary Variable

This is the safest, simplest, and most widely used approach.

Java Program

public class Main {

    public static void main(String[] args) {

        int a = 10;
        int b = 20;

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

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

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

Output

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

This method is recommended for production code because it is easy to understand, works for every data type, and never risks overflow.

Time Complexity

O(1)

Space Complexity

O(1)


Method 2: Swap Without a Third Variable (Addition and Subtraction)

This method uses arithmetic operations to swap values.

Java Program

public class Main {

    public static void main(String[] args) {

        int a = 10;
        int b = 20;

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

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

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

Output

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

Although this method avoids using a third variable, it can produce incorrect results if the addition operation exceeds the maximum value an int can store.

Time Complexity

O(1)

Space Complexity

O(1)


Method 3: Swap Without a Third Variable (Multiplication and Division)

Another arithmetic approach uses multiplication and division.

Java Program

public class Main {

    public static void main(String[] args) {

        int a = 10;
        int b = 20;

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

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

Output

After swapping: a = 20, b = 10

This method should generally be avoided because it can overflow more easily than addition and fails if either variable contains zero.

Time Complexity

O(1)

Space Complexity

O(1)


Method 4: Swap Using the Bitwise XOR Operator

The XOR operator swaps values without using an extra variable or arithmetic operations.

Java Program

public class Main {

    public static void main(String[] args) {

        int a = 10;
        int b = 20;

        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

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

Output

After swapping: a = 20, b = 10

The XOR method avoids overflow and division-by-zero problems, but it only works with integer types and is less readable than the temporary-variable approach.

Time Complexity

O(1)

Space Complexity

O(1)


How Java Handles Swapping Internally

Consider the variables:

int a = 10;
int b = 20;

Internally:

  1. a and b are primitive integers stored in the stack memory.

  2. In Method 1, a third stack variable named temp temporarily stores one value.

  3. In Methods 2, 3, and 4, Java repeatedly updates the same two memory locations without allocating an additional variable.

  4. No heap memory is used because primitive variables are stored directly in the method's stack frame.

  5. After the main() method finishes execution, all local variables are automatically removed from memory.


Real-Life Analogy

Imagine two glasses:

  • Glass A contains orange juice.

  • Glass B contains apple juice.

Using a temporary variable is like using a third empty glass.

  1. Pour Glass A into the empty glass.

  2. Pour Glass B into Glass A.

  3. Pour the contents of the empty glass into Glass B.

Without the third glass, you need clever tricks to exchange the contents without losing either one—just like the arithmetic and XOR methods.


Comparison of Different Methods

Method Extra Variable Overflow Risk Divide by Zero Recommended
Temporary Variable Yes No No ⭐⭐⭐⭐⭐
Addition/Subtraction No Yes No ⭐⭐⭐
Multiplication/Division No Yes Yes
XOR Operator No No No ⭐⭐⭐⭐

Best Practices

  • Prefer the temporary-variable method in production code.

  • Use arithmetic or XOR methods mainly for coding interviews.

  • Avoid the multiplication/division method because of divide-by-zero and overflow risks.

  • Use descriptive variable names.

  • When swapping array elements, always use the temporary-variable approach for maximum readability.


Common Mistakes

Overwriting a Value

Incorrect:

a = b;
b = a;

After the first statement, the original value of a is permanently lost.


Ignoring Integer Overflow

The addition/subtraction method can overflow when working with very large integers.


Division by Zero

The multiplication/division approach throws an ArithmeticException if either variable is zero.


Using XOR with Floating-Point Values

The XOR operator works only with integer types and cannot be applied to float or double values.


Assuming Swapping Primitive Parameters Changes the Caller

Java passes primitive values by value, so swapping local parameters inside a method does not affect the original variables outside that method.


Expert Tips

  • Start with the temporary-variable solution during interviews.

  • Mention arithmetic and XOR methods only as alternatives.

  • Explain why the temporary-variable method is preferred in production code.

  • Highlight the overflow issue in the arithmetic approach and the divide-by-zero issue in the multiplication/division approach.


Pros and Cons

Method Advantages Disadvantages
Temporary Variable Safe, readable, works for all data types Uses one additional variable
Addition/Subtraction No extra variable Can overflow
Multiplication/Division No extra variable Overflow and divide-by-zero risk
XOR Operator No overflow, no division Integer types only and less readable

Frequently Asked Questions

What is the easiest way to swap two numbers in Java?

Use a temporary variable.

It is the safest and most readable solution.


How can I swap two numbers without using a third variable?

You can use:

  • Addition and subtraction

  • Multiplication and division

  • Bitwise XOR


Why can the addition/subtraction method fail?

If the intermediate sum exceeds the maximum value an int can store, integer overflow occurs.


Is the XOR method used in production code?

Rarely.

Although it works well, the temporary-variable method is much easier to read and maintain.


Can I use multiplication and division to swap numbers?

Yes, but it is not recommended because it fails when either value is zero and is more susceptible to overflow.


Does swapping work with floating-point numbers?

Yes.

The temporary-variable and arithmetic methods work for float and double.

The XOR method does not.


What are the time and space complexities?

All methods execute in constant time.

Time Complexity: O(1)

Space Complexity: O(1)


How do I swap two elements in an array?

Use a temporary variable:

int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

This technique is widely used in sorting algorithms.


Can I swap two objects?

Yes.

The temporary-variable method works for object references as well.


Why is this question frequently asked in interviews?

It tests your understanding of variable assignment, memory usage, arithmetic operations, and alternative problem-solving techniques.


What happens if both variables already have the same value?

All four methods still work correctly.

The values remain unchanged after swapping.


Does Java provide a built-in swap method?

No.

Java has no built-in method for swapping primitive variables.

However, classes like Collections provide methods such as Collections.swap() for swapping elements inside a List.