Java
programming
array manipulation
element swapping
coding techniques

Efficient swapping of elements of an array in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Swapping array elements is a simple operation, but it appears in many performance-sensitive algorithms such as sorting, partitioning, and heap operations. In Java, the safest and usually fastest approach uses a temporary variable. Alternatives like XOR swap or arithmetic swap are mostly educational and can introduce correctness problems.

Standard Swap with Temporary Variable

The canonical Java swap for primitive arrays is straightforward.

java
1public static void swap(int[] arr, int i, int j) {
2    int temp = arr[i];
3    arr[i] = arr[j];
4    arr[j] = temp;
5}

Why this remains best practice:

  • clear intent
  • works for all value patterns
  • no overflow or bit-level surprises
  • optimized well by modern JIT compilers

Readability and reliability are usually more important than clever micro-optimizations.

Add Bounds and Identity Checks

Production utilities should validate indexes and avoid unnecessary writes when both indexes are equal.

java
1public static void safeSwap(int[] arr, int i, int j) {
2    if (arr == null) {
3        throw new IllegalArgumentException("array cannot be null");
4    }
5    if (i < 0 || i >= arr.length || j < 0 || j >= arr.length) {
6        throw new IndexOutOfBoundsException("swap index out of range");
7    }
8    if (i == j) {
9        return;
10    }
11
12    int temp = arr[i];
13    arr[i] = arr[j];
14    arr[j] = temp;
15}

These checks prevent subtle bugs in generic algorithm code.

Swapping Generic Object Arrays

For object arrays, logic is identical but uses references.

java
1public static <T> void swap(T[] arr, int i, int j) {
2    T temp = arr[i];
3    arr[i] = arr[j];
4    arr[j] = temp;
5}

This works for String[], custom class arrays, and boxed types.

Why XOR Swap Is Usually a Bad Idea

XOR swap is a well-known trick:

java
1public static void xorSwap(int[] arr, int i, int j) {
2    if (i == j) return;
3    arr[i] ^= arr[j];
4    arr[j] ^= arr[i];
5    arr[i] ^= arr[j];
6}

Even though it can work, it is generally discouraged because:

  • much less readable
  • easy to break if index alias checks are forgotten
  • no practical performance advantage on modern JVM

In real code, clarity and maintainability win.

Arithmetic Swap Risks Overflow

Arithmetic swap pattern can overflow for large integers.

java
1// avoid this in production
2arr[i] = arr[i] + arr[j];
3arr[j] = arr[i] - arr[j];
4arr[i] = arr[i] - arr[j];

Even if values are within int range individually, intermediate sums may exceed bounds. That makes this method unsafe for general use.

Swapping in Sorting Algorithms

Swapping is often called thousands of times during sorting. Keep swap function compact and predictable.

Example quicksort partition using safe temp swap:

java
1public static int partition(int[] arr, int low, int high) {
2    int pivot = arr[high];
3    int i = low - 1;
4
5    for (int j = low; j < high; j++) {
6        if (arr[j] <= pivot) {
7            i++;
8            int temp = arr[i];
9            arr[i] = arr[j];
10            arr[j] = temp;
11        }
12    }
13
14    int temp = arr[i + 1];
15    arr[i + 1] = arr[high];
16    arr[high] = temp;
17
18    return i + 1;
19}

Inline swap in hot code paths is common and still readable.

Utility Methods in Java Collections

When working with List, use standard library helper:

java
1import java.util.*;
2
3List<Integer> values = new ArrayList<>(Arrays.asList(10, 20, 30));
4Collections.swap(values, 0, 2);
5System.out.println(values); // [30, 20, 10]

For arrays, there is no direct Collections.swap, so custom helper remains normal.

Performance Notes

For primitive arrays, temporary-variable swap is already efficient. If profiling shows swap overhead, focus on algorithm-level improvements first, such as reducing unnecessary comparisons or memory access patterns.

Micro-optimizing swap logic alone rarely changes end-to-end runtime significantly unless called in extremely tight loops where compiler behavior has already been measured.

Testing Swap Logic

Minimal tests should include:

  • swapping different valid indexes
  • swapping same index
  • swapping first and last elements
  • invalid indexes throwing expected exceptions
  • null array handling

Small unit tests prevent regressions when refactoring shared utility code.

Common Pitfalls

  • Using XOR or arithmetic swap in production for perceived speed gains.
  • Forgetting index validation in reusable swap helpers.
  • Not handling i == j when using non-standard swap techniques.
  • Confusing object reference swap with deep-copy semantics.
  • Optimizing swap method before profiling actual algorithm bottlenecks.

Summary

  • The temporary-variable swap is the recommended Java approach for correctness and readability.
  • Add validation in reusable utilities to prevent index-related bugs.
  • Avoid XOR and arithmetic swaps in production code.
  • Use Collections.swap for lists and custom helpers for arrays.
  • Algorithm design usually matters more than swap micro-optimizations for performance.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.