How to Swap Two Variables in Java
The Challenge
Exchange the values of two variables - like trading cards with a friend!
Solution
Method 1: Using a Temporary Variable
int a = 5;
int b = 10;
System.out.println("Before swap: a = " + a + ", b = " + b);
// Swap using temp variable
int temp = a;
a = b;
b = temp;
System.out.println("After swap: a = " + a + ", b = " + b);
// Output: Before swap: a = 5, b = 10
// After swap: a = 10, b = 5Method 2: Without Temporary Variable (Addition/Subtraction)
int a = 5;
int b = 10;
a = a + b; // a = 15
b = a - b; // b = 5
a = a - b; // a = 10
System.out.println("a = " + a + ", b = " + b);
// Output: a = 10, b = 5Method 3: Using XOR (Bitwise)
int a = 5;
int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a = " + a + ", b = " + b);
// Output: a = 10, b = 5Did You Know?
The temporary variable method is the most readable and recommended approach. The arithmetic and XOR methods are clever but can be confusing and may cause overflow issues!
Watch Out!
The addition method can cause integer overflow for large numbers:
int a = Integer.MAX_VALUE;
int b = 100;
// a + b will overflow! Use temp variable instead.Real-World Use Cases
- Sorting algorithms: Swap elements to sort arrays
- Game development: Swap player positions
- Data structures: Rearrange linked list nodes
›Short versionOpen if you only have a minute.
- A temporary variable is the swap reviewers can check in one glance.
- Assigning a = b first drops the old value of a. There is nothing left to write into b.
- Arithmetic and XOR swaps fail on overflow, on identical indexes, and on non-integers.
- Swapping two references exchanges which object each variable names. It does not copy fields.
Swap two variables
Exchange two variable values without losing either original value.
Working approach
- Copy the first value into a temporary, then assign the second into the first, then the temporary into the second.
- Keep both variables the same type.
- Use the same three assignments for two array slots, and skip the work when the indexes are equal.
Walk the sample
- Start: a = 5, b = 9
- temp = a stores 5
- a = b makes a 9
- b = temp makes b 5
The trap
a = a + b can overflow, and a ^= b; b ^= a; a ^= b sets the slot to 0 when both sides are the same array element.
int temp = a;
a = b;
b = temp;
// array slots: do nothing when i == j
if (i != j) {
int held = values[i];
values[i] = values[j];
values[j] = held;
}What does an XOR swap do when both sides are values[i] and i == j?
Both sides name the same int. The first XOR clears it to 0, and the later XORs keep 0.
A temporary copy does not have that aliasing bug, and it works for references as well as ints.
Time O(1), space O(1).
Easy to get wrong
- Writing a = b before saving the old a.
- Using an arithmetic swap on values near the top of the int range.