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.
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.
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.
These checks prevent subtle bugs in generic algorithm code.
Swapping Generic Object Arrays
For object arrays, logic is identical but uses references.
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:
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.
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:
Inline swap in hot code paths is common and still readable.
Utility Methods in Java Collections
When working with List, use standard library helper:
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 == jwhen 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.swapfor lists and custom helpers for arrays. - Algorithm design usually matters more than swap micro-optimizations for performance.
Related reading
- Efficient time and space complexity data structure for dense and sparse matrix
- Efficient way to compare two arrays
- Efficient way to find degrees of separation between two nodes in a graph
- Efficient way to insert a number into a sorted array of numbers?
- Ehcache - using a ListInteger as the cache value
- EHCache RMI Replication on JBoss/EC2 throws java.rmi.NoSuchObjectException no such object in table
- Efficient way to remove half of the duplicate items in a list
- Efficient way to rotate a list in python

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 courseTrack 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.