Swapping two variables is a common task in programming. Traditionally, we use a temporary variable to hold one value while swapping, but Java allows us to swap two variables without using a temp variable.
In this tutorial, we will explore different ways to achieve this in Java with real-world examples.
Table of contents:
- 1. Swapping Using Arithmetic Operators
- 2. Swapping Using Multiplication and Division
- 3. Swapping Using Bitwise XOR Operator
- 4. Understanding XOR (^) Operator in Java for Swapping Two Variables
- Which Method Should You Use?
- References
P.S Tested with Java 21
1. Swapping Using Arithmetic Operators
We can swap two numbers using addition (+) and subtraction (-).
package com.mkyong;
public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swap: a = " + a + ", b = " + b);
// Swap using arithmetic operations
a = a + b;
b = a - b;
a = a - b;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Output:
Before Swap: a = 10, b = 20
After Swap: a = 20, b = 10
Explanation:
a = a + b;→anow holds the sum ofaandb(10 + 20 = 30).b = a - b;→bnow gets the original value ofa(30 - 20 = 10).a = a - b;→anow gets the original value ofb(30 - 10 = 20).
Note:
This method may cause an integer overflow if a + b exceeds the maximum value for integers (Integer.MAX_VALUE).
2. Swapping Using Multiplication and Division
Another alternative is to use multiplication (*) and division (/), but it only works if neither a nor b is zero.
package com.mkyong;
public class SwapUsingMultiplication {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swap: a = " + a + ", b = " + b);
// Swap using multiplication and division
a = a * b;
b = a / b;
a = a / b;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Explanation:
a = a * b;→aholds the product ofaandb.b = a / b;→bgets the original value ofa.a = a / b;→agets the original value ofb.
Output:
Before Swap: a = 10, b = 20
After Swap: a = 20, b = 10
Limitations:
- This method does not work if either
aorbis zero. - It may cause overflow with large numbers.
3. Swapping Using Bitwise XOR Operator
The XOR bitwise operator (^) is an efficient way to swap two variables without using extra space.
package com.mkyong;
public class SwapUsingXOR {
public static void main(String[] args) {
int x = 10, y = 20;
System.out.println("Before Swap: x = " + x + ", y = " + y);
// Swap using XOR
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("After Swap: x = " + x + ", y = " + y);
}
}
Output:
Before Swap: x = 10, y = 20
After Swap: x = 20, y = 10
Explanation:
x = x ^ y;→xnow holds the XOR result ofxandy.y = x ^ y;→ygets the original value ofx.x = x ^ y;→xgets the original value ofy.
Why Use XOR?
- This method works well with integer values.
- It does not suffer from integer overflow issues like the arithmetic method.
- However, it may not be as readable as the addition-subtraction method.
4. Understanding XOR (^) Operator in Java for Swapping Two Variables
The bitwise XOR (^) operator is a powerful tool in Java that allows us to manipulate individual bits of integers. It is commonly used in programming for tasks like encryption, error detection, and variable swapping.
What is XOR (^) Operator?
The XOR (exclusive OR) operator compares each bit of two numbers. It returns 1 if the bits are different and 0 if they are the same.
XOR Truth Table
| A | B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Example: XOR of Two Numbers
Let’s take two numbers:
5 (0101 in binary) and 8 (1000 in binary)
| Bit Position | 5 (0101) | 8 (1000) | 5 ^ 8 |
|---|---|---|---|
| 1st bit | 1 | 0 | 1 |
| 2nd bit | 0 | 0 | 0 |
| 3rd bit | 1 | 0 | 1 |
| 4th bit | 0 | 1 | 1 |
Result:
5 = 0101
8 = 1000
----------------
5 ^ 8 = 1101 (which is 13 in decimal)
How XOR Works for Swapping Two Numbers
The XOR operator has a special property:
- If we apply XOR twice with the same number, the original value is restored.
That is:
X ^ Y ^ Y = X
This property allows us to swap two numbers without using a temporary variable.
Swapping Two Numbers Using XOR
Let’s break down the swap step by step:
package com.mkyong;
public class SwapUsingXOR {
public static void main(String[] args) {
int x = 5, y = 8;
System.out.println("Before Swap: x = " + x + ", y = " + y);
// Step 1: XOR both numbers and store result in x
x = x ^ y; // x now holds (5 ^ 8) = 13
// Step 2: XOR x with y and store result in y
y = x ^ y; // y now holds (13 ^ 8) = 5 (original value of x)
// Step 3: XOR x with new y and store result in x
x = x ^ y; // x now holds (13 ^ 5) = 8 (original value of y)
System.out.println("After Swap: x = " + x + ", y = " + y);
}
}
Step-by-Step Explanation of XOR Swap
Let’s assume x = 5 (0101 in binary) and y = 8 (1000 in binary).
Step 1: Compute x = x ^ y
5 = 0101
8 = 1000
----------------
x = 5 ^ 8 = 1101 (which is 13 in decimal)
Now, x = 13 and y = 8.
Step 2: Compute y = x ^ y
13 = 1101
8 = 1000
----------------
y = 13 ^ 8 = 0101 (which is 5 in decimal)
Now, x = 13 and y = 5 (original x value is now in y).
Step 3: Compute x = x ^ y
13 = 1101
5 = 0101
----------------
x = 13 ^ 5 = 1000 (which is 8 in decimal)
Now, x = 8 and y = 5. Swap is complete! 🎉
Advantages of Using XOR for Swapping
✅ No extra memory needed – We don’t use a temporary variable.
✅ Works for all integers – Unlike arithmetic methods, there’s no risk of integer overflow.
✅ Efficient bitwise operation – XOR is a low-level operation and works efficiently in hardware.
Disadvantages of XOR Swap
❌ Less readable – XOR swap is not as intuitive as using a temp variable.
❌ Doesn’t work well with floating-point numbers – Works only with integers.
❌ Hard to debug – If not careful, mistakes can be hard to trace.
Which Method Should You Use?
| Method | Pros | Cons |
|---|---|---|
| Addition/Subtraction | Simple and easy to understand | Risk of integer overflow |
| Bitwise XOR | No risk of overflow, works well with integers | Less readable |
| Multiplication/Division | Works well with non-zero values | Cannot handle zeros, risk of overflow |