How do you swap two numbers without using a third variable in Java?
- User
How do you swap two numbers without using a third variable in Java?
- Assistant
Of course! This is a classic interview question. While using a third variable is the most readable and standard approach, you can swap two numbers without one using a couple of clever techniques.
Here are the two most common methods in Java.
Method 1: Using Arithmetic Operators (Addition and Subtraction)
This method uses a series of additions and subtractions to store the combined value of both numbers in one of the variables and then unravel them.
The Code
public class SwapWithArithmetic { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("--- Before Swap ---"); System.out.println("a = " + a); System.out.println("b = " + b); // Step 1: a becomes the sum of both numbers (a = 10 + 20 = 30) a = a + b; // Step 2: b becomes the original value of a (b = 30 - 20 = 10) b = a - b; // Step 3: a becomes the original value of b (a = 30 - 10 = 20) a = a - b; System.out.println("\n--- After Swap ---"); System.out.println("a = " + a); System.out.println("b = " + b); } }How it Works
Let's trace the values of
aandb.- Initial State:
a = 10,b = 20 a = a + b;:ais now10 + 20 = 30.bis still20. The variableanow holds the information of both original numbers.b = a - b;:bis now30 - 20 = 10. This calculation effectively subtracts the originalbfrom the sum, leaving the originala.a = a - b;:ais now30 - 10 = 20. This subtracts the new value ofb(which is the originala) from the sum, leaving the originalb.
Drawback
This method can fail due to integer overflow. If
a + bis larger than the maximum value for the integer type (e.g.,Integer.MAX_VALUE), the sum will overflow and wrap around, leading to incorrect results.
Method 2: Using the Bitwise XOR (^) Operator
This is generally considered the best and safest method for swapping without a third variable because it avoids the overflow problem. It relies on the properties of the XOR operation.
Key XOR Properties:
x ^ x = 0(A number XORed with itself is zero)x ^ 0 = x(A number XORed with zero is itself)x ^ y = y ^ x(Commutative)(x ^ y) ^ y = x(The key property for this swap!)
The Code
public class SwapWithXOR { public static void main(String[] args) { int a = 10; // Binary: 00001010 int b = 20; // Binary: 00010100 System.out.println("--- Before Swap ---"); System.out.println("a = " + a); System.out.println("b = " + b); // The magic happens here a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("\n--- After Swap ---"); System.out.println("a = " + a); System.out.println("b = " + b); } }How it Works
Let's trace the values using the variables themselves.
- Initial State:
a = original_a,b = original_b a = a ^ b;:anow holds the result oforiginal_a ^ original_b.bis unchanged.b = a ^ b;: This translates tob = (original_a ^ original_b) ^ original_b. Because of property #4, this simplifies tob = original_a. The swap forbis complete!a = a ^ b;: This translates toa = (original_a ^ original_b) ^ original_a. Because XOR is commutative, this is the same asa = (original_a ^ original_a) ^ original_b. This simplifies toa = 0 ^ original_b, which isa = original_b. The swap forais complete!
This method works flawlessly with any integer type and does not suffer from overflow issues.
Summary and Recommendation
Method Pros Cons Using a Temp Variable (Standard) Extremely readable, works for all data types (including objects), no side effects. Uses one extra variable (negligible memory impact). Arithmetic (Add/Subtract) No extra variable. Less readable, can fail due to integer overflow. Bitwise XOR (^) No extra variable, does not overflow. Less readable for developers unfamiliar with bitwise operations. Which one should you use?
-
In real-world production code: Always use the temporary variable.
int temp = a; a = b; b = temp;Code is written for humans to read and maintain. The clarity and obvious intent of the temporary variable method far outweigh the microscopic performance or memory gain of the other methods. Modern compilers and JIT (Just-In-Time) optimizers are so smart that they might optimize all three versions to the same underlying machine code anyway.
-
In a technical interview: Know all three methods. Explain the pros and cons of each. Start by saying you'd use a temp variable in production code for clarity, but then demonstrate your knowledge of the arithmetic and (especially) the XOR methods to answer the specific question asked. The XOR swap is the classic, "correct" answer to this puzzle.
- Initial State:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.