Sorting Algorithms ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-07-23

How to Swap Variables in Java

Swapping means exchanging the values of two variables: what was stored in the first ends up in the second, and vice versa. You reach for this constantly when sorting, reordering elements, or solving algorithm problems. Below are three ways to swap two variables in Java, plus a separate look at why a swap method for ordinary variables does not behave the way beginners expect.

Swap using a temporary variable

The simplest and most reliable approach. Introduce a temporary variable tmp that holds the value from the first variable while we overwrite it with the value from the second:

int tmp = a;
a = b;
b = tmp;

Full example:

public class SwapExample1 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        int tmp = a;
        a = b;
        b = tmp;

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Output:

a = 5
b = 3

This version works with any type — int, double, String, object references — and has no hidden traps. It is the one you should reach for by default.

Swap without a temporary variable (arithmetic)

Sometimes you are asked to swap values without a third variable. One option is addition and subtraction:

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

Full example with a step-by-step breakdown in the comments:

public class SwapExample2 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        a = a + b; // a = 8, b = 5
        b = a - b; // a = 8, b = 3
        a = a - b; // a = 5, b = 3

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Watch out for overflow

The sum a + b can exceed the range of int (from minus 2,147,483,648 to 2,147,483,647). When it overflows, the intermediate result wraps around; the final swap still comes out correct because the same wrap cancels out during subtraction, but relying on that in real code is a bad idea. For double and float the arithmetic trick is unreliable due to precision loss. In production, prefer the temporary-variable swap.

Swap using XOR

Another no-temp trick is the bitwise exclusive OR (^). It works only for integer types, but it has no overflow problem:

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

Full example:

public class SwapExample3 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

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

        System.out.println("a = " + a); // a = 5
        System.out.println("b = " + b); // b = 3
    }
}

It works thanks to two properties of XOR: x ^ x == 0 and x ^ 0 == x. One gotcha: if you accidentally apply this swap to the same variable (for example arr[i] and arr[j] when i == j), it zeroes the value out. XOR swapping looks clever in an interview, but in ordinary code it loses to the temporary variable on readability.

Why a swap() method does not change the variables

It is tempting to move the swap into a reusable swap method. But with primitives that will not work — Java always passes arguments by value: the method receives copies, not the variables themselves.

public class SwapMethod {

    // Does NOT work: x and y are copies, the originals a and b stay unchanged
    static void swap(int x, int y) {
        int tmp = x;
        x = y;
        y = tmp;
    }

    public static void main(String[] args) {
        int a = 3;
        int b = 5;
        swap(a, b);
        System.out.println("a = " + a); // a = 3
        System.out.println("b = " + b); // b = 5 - nothing was swapped
    }
}

This is one of the most common interview traps. A universal swap(int, int) method for two local variables is simply impossible in Java. The workaround is to pass not the values themselves but a container whose contents you can modify from inside: an array, a list, or a wrapper object.

Swapping array and list elements

When the values live in an array, a swap method works perfectly: the method gets a copy of the reference, but it still points to the same array object, so element changes are visible to the caller.

static void swap(int[] arr, int i, int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

For collections, the standard library already ships Collections.swap, which exchanges two list elements by their indices:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SwapList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("A", "B", "C"));
        Collections.swap(list, 0, 2);
        System.out.println(list); // [C, B, A]
    }
}

Which one to use in practice

Method Types Pros Cons
Temporary variable Any Simple, reliable, readable Needs one extra variable (negligible)
Addition and subtraction Integers No third variable Overflow risk, harder to read
XOR (^) Integers No overflow, no third variable Breaks when swapping an element with itself
Collections.swap List elements Built-in JDK method Lists only

The takeaway is simple: in real code, almost always use the temporary-variable swap — it is clear, works with any type, and has no hidden limits. The arithmetic and XOR tricks are worth knowing for interviews, but in production they only make the code harder to read. And when you need to swap values "in the caller", remember pass-by-value: work through an array, a list, or a wrapper object.

Frequently asked questions

How do I write a swap method for two variables in Java?

For two ordinary (primitive) variables you cannot: Java passes arguments by value, so the method receives copies and the originals stay unchanged. Swapping works only if you pass a container — an array, a List, or a wrapper object — and modify its contents inside the method. For local variables, swap them inline without a method.

How do I swap two variables without a third variable?

Two tricks. With arithmetic: a = a + b; b = a - b; a = a - b; — but there is an overflow risk. With XOR: a = a ^ b; b = a ^ b; a = a ^ b; — no overflow, but integers only. In real code the temporary-variable swap is easier and safer.

Is the addition-and-subtraction swap safe?

For integers the result is always correct, because the overflow during addition is cancelled out during subtraction. Still, relying on overflow in production is unwise, and for double and float the method is unreliable due to precision loss. Prefer the temporary-variable swap.

How do I swap two array or list elements?

For an array, write a method that takes the array and two indices and swaps the elements through a temporary variable — the changes are visible to the caller because the method works on the same object. For a list, use the built-in Collections.swap(list, i, j).

Comments

Please log in or register to have a possibility to add comment.