How to Swap Two Elements in an Array in Java
Swapping two elements is one of the simplest array operations in Java, yet it forms the foundation of many algorithms. Popular sorting techniques such as Bubble Sort, Selection Sort, and Quick Sort all rely on swapping elements repeatedly.
In this tutorial, you'll learn multiple ways to swap two elements in a Java array, understand how each approach works internally, and discover why the traditional temporary-variable method remains the preferred choice in professional Java development.
Problem Statement
Given the following array:
int[] numbers = {10, 20, 30, 40, 50};
Swap the elements at indices 1 and 3.
Before swapping:
[10, 20, 30, 40, 50]
After swapping:
[10, 40, 30, 20, 50]
Method 1: Using a Temporary Variable (Recommended)
The most common and recommended approach is to use a temporary variable to hold one value while the other value is moved.
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int temp = numbers[1];
numbers[1] = numbers[3];
numbers[3] = temp;
System.out.println(Arrays.toString(numbers));
}
}
Output
[10, 40, 30, 20, 50]
Explanation
- Store the value at index 1 inside the temporary variable.
- Copy the value from index 3 to index 1.
- Copy the saved value from the temporary variable back to index 3.
This method is:
- Easy to understand
- Works for every data type
- Safe and reliable
- Used in production-quality Java code
Method 2: Arithmetic Swap (Without Temporary Variable)
Another technique swaps values using addition and subtraction.
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int i = 1;
int j = 3;
numbers[i] = numbers[i] + numbers[j];
numbers[j] = numbers[i] - numbers[j];
numbers[i] = numbers[i] - numbers[j];
System.out.println(Arrays.toString(numbers));
}
}
Output
[10, 40, 30, 20, 50]
How It Works
Initially,
numbers[1] = 20
numbers[3] = 40
After first statement:
numbers[1] = 20 + 40 = 60
After second statement:
numbers[3] = 60 - 40 = 20
After third statement:
numbers[1] = 60 - 20 = 40
The values are successfully exchanged.
Limitation
This method may cause integer overflow if the addition exceeds Java's int range, making it unsafe for large numbers.
Method 3: XOR Swap (Without Temporary Variable)
The XOR operator can also swap two integers without using extra memory.
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int i = 1;
int j = 3;
numbers[i] = numbers[i] ^ numbers[j];
numbers[j] = numbers[i] ^ numbers[j];
numbers[i] = numbers[i] ^ numbers[j];
System.out.println(Arrays.toString(numbers));
}
}
Output
[10, 40, 30, 20, 50]
How It Works
Suppose:
numbers[1] = 20
numbers[3] = 40
The XOR operator temporarily combines both values.
After performing the three XOR operations:
- The original value of index 1 moves to index 3.
- The original value of index 3 moves to index 1.
No additional variable is required.
Limitation
If both indices are the same:
i == j
the XOR method changes the value to 0, producing an incorrect result.
Why the Temporary Variable Method Is Still Preferred
Although arithmetic and XOR swaps are clever programming tricks, professional Java developers almost always use the temporary-variable approach.
Reasons include:
- It works with every data type, including objects and strings.
- There is no risk of integer overflow.
- It safely handles swapping an element with itself.
- It is easy to read and maintain.
- Every Java developer immediately understands it.
The other techniques are useful for interviews and understanding bitwise operations but are rarely used in production code.
Step-by-Step Explanation
Consider the array:
[10, 20, 30, 40, 50]
Step 1
Store the first value.
temp = numbers[1];
temp = 20
Step 2
Copy the second value into the first position.
numbers[1] = numbers[3];
Array becomes:
[10, 40, 30, 40, 50]
Step 3
Restore the saved value.
numbers[3] = temp;
Final array:
[10, 40, 30, 20, 50]
Internal Working
Initial State
numbers = [10, 20, 30, 40, 50]
↑ ↑
i=1 j=3
After Saving Value
temp = 20
After First Assignment
numbers = [10, 40, 30, 40, 50]
After Second Assignment
numbers = [10, 40, 30, 20, 50]
Final Result
[10, 40, 30, 20, 50]
The temporary variable exists only during the swap operation and stores the original value until the exchange is complete.
Real-Life Analogy
Imagine two labeled boxes containing different objects.
If you want to exchange their contents, you cannot simply pour the contents of Box A into Box B because Box B's original contents would be lost.
Instead:
- Put Box A's contents into a temporary container.
- Move Box B's contents into Box A.
- Move the temporary container's contents into Box B.
The temporary container acts exactly like the temporary variable in Java.
Best Practices
- Prefer the temporary-variable method for production code.
- Use arithmetic and XOR swaps only for learning or interview discussions.
- Always check if both indices are the same before swapping.
- Create a reusable
swap()method if swapping occurs frequently.
Example:
public static void swap(int[] arr, int i, int j) {
if (i == j) {
return;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Common Mistakes
1. Forgetting the Temporary Variable
Incorrect code:
numbers[i] = numbers[j];
numbers[j] = numbers[i];
Both positions end up storing the same value.
2. Using XOR on the Same Index
swap(arr, 2, 2);
The XOR method incorrectly changes the value to zero.
3. Ignoring Integer Overflow
Arithmetic swapping can fail when values become too large during addition.
4. Using Numeric Tricks with Objects
Arithmetic and XOR swapping work only for primitive numeric types.
They cannot be used with:
- String arrays
- Object arrays
- Custom class objects
Expert Tips
- Add a guard clause before swapping:
if (i == j) {
return;
}
- Create a reusable utility method instead of repeating swap logic.
- Master swapping before learning sorting algorithms because nearly every sorting algorithm depends on it.
- For arrays of objects, always use the temporary-variable approach.
Comparison Table
| Method | Works for Any Type? | Overflow Risk | Same-Index Safe? | Recommended? |
|---|---|---|---|---|
| Temporary Variable | ✅ Yes | None | ✅ Yes | ✅ Yes |
| Arithmetic Swap | ❌ Numbers Only | ⚠️ Yes | ✅ Yes | ❌ No |
| XOR Swap | ❌ Integers Only | None | ❌ No | ❌ No |
Frequently Asked Questions
1. What is the safest way to swap two array elements in Java?
Using a temporary variable is the safest and most commonly used method because it works for every data type and has no overflow issues.
2. Can I swap array elements without using a temporary variable?
Yes. You can use arithmetic operations or the XOR operator, but both approaches have limitations and are generally avoided in production code.
3. Why does the XOR swap fail when both indices are the same?
When both indices refer to the same element, XORing a value with itself produces zero, causing the original value to be lost.
4. Is arithmetic swapping always safe?
No. If the addition exceeds the maximum value that an int can store, integer overflow occurs, resulting in incorrect values.
5. Can I use XOR swapping with String arrays?
No. XOR swapping only works with integer primitive types. For strings and objects, always use the temporary-variable method.