Swap Two Numbers
Java coding interview problem for Basic Number Programs: Swap Two Numbers.
Swapping two numbers is one of the most fundamental Java coding interview questions. Although the logic is simple, interviewers use this problem to evaluate your understanding of variables, assignments, arithmetic operations, and problem-solving skills.
It is one of the first coding questions asked during Java, C, C++, and programming interviews.
What is Swapping?
Swapping means exchanging the values of two variables.
Before swapping
A = 10
B = 20
After swapping
A = 20
B = 10
The values are exchanged while the variable names remain the same.
Real Interview Question
Write a Java program to swap two numbers.
Example 1
Input
A = 10
B = 20
Output
A = 20
B = 10
Example 2
Input
A = 100
B = 500
Output
A = 500
B = 100
Example 3
Input
A = -5
B = 15
Output
A = 15
B = -5
Understanding the Logic
The easiest way to swap two numbers is by using a temporary variable.
A temporary variable stores one value while the other variable is updated.
The process is
A
↓
Temp
↓
B
↓
A
Visual Representation
Initially
+-------+ +-------+
| A | 10 | B | 20
+-------+ +-------+
Store A inside Temp
Temp = 10
Copy B into A
A = 20
Copy Temp into B
B = 10
Final
+-------+ +-------+
| A | 20 | B | 10
+-------+ +-------+
Brute Force Approach
The simplest and safest approach is
- Store the first value in a temporary variable.
- Copy the second value into the first variable.
- Copy the temporary value into the second variable.
This is the approach most beginners learn first.
Algorithm
Step 1
Read two numbers.
A
B
Step 2
Create a temporary variable.
temp
Step 3
Store the first value.
temp = a;
Step 4
Copy the second value.
a = b;
Step 5
Copy the temporary value.
b = temp;
Step 6
Print the swapped numbers.
Dry Run
Input
A = 10
B = 20
| Step | A | B | Temp |
|---|---|---|---|
| Initial | 10 | 20 | - |
| Temp = A | 10 | 20 | 10 |
| A = B | 20 | 20 | 10 |
| B = Temp | 20 | 10 | 10 |
Final Output
A = 20
B = 10
Another Dry Run
Input
A = 45
B = 75
| Step | A | B | Temp |
|---|---|---|---|
| Initial | 45 | 75 | - |
| Temp = A | 45 | 75 | 45 |
| A = B | 75 | 75 | 45 |
| B = Temp | 75 | 45 | 45 |
Output
A = 75
B = 45
Approach 1 — Using a Temporary Variable
This is the most common and recommended approach.
Complete Java Program
public class SwapTwoNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before Swapping");
System.out.println("A = " + a);
System.out.println("B = " + b);
int temp = a;
a = b;
b = temp;
System.out.println();
System.out.println("After Swapping");
System.out.println("A = " + a);
System.out.println("B = " + b);
}
}
Output
Before Swapping
A = 10
B = 20
After Swapping
A = 20
B = 10
Step-by-Step Code Explanation
Step 1
Declare two variables.
int a = 10;
int b = 20;
Current values
A = 10
B = 20
Step 2
Create a temporary variable.
int temp;
The temporary variable is used to preserve one value during the swap.
Step 3
Store the first value.
temp = a;
Now
Temp = 10
A = 10
B = 20
Step 4
Assign the second value to the first variable.
a = b;
Now
A = 20
B = 20
Temp = 10
Notice that the original value of A is safely stored in Temp.
Step 5
Assign the temporary value to the second variable.
b = temp;
Now
A = 20
B = 10
The values have been successfully exchanged.
Step 6
Display the result.
System.out.println("A = " + a);
System.out.println("B = " + b);
Output
A = 20
B = 10
Why Does This Work?
The temporary variable acts as a safe storage location.
Without it, assigning
a = b;
would overwrite the original value of A, making it impossible to recover.
The temporary variable prevents data loss by preserving the original value until the swap is complete.
Advantages of This Approach
- Very easy to understand.
- Most readable solution.
- No risk of integer overflow.
- Works for all numeric data types.
- Recommended for beginners.
- Preferred in production code because of its clarity.
Drawbacks
The only drawback is that it uses one extra variable.
Although this requires only constant extra memory, interviewers often ask a follow-up question:
"Can you swap two numbers without using a temporary variable?"
In the next part, we'll explore multiple techniques to swap numbers without a temporary variable, including:
- Addition and subtraction method
- Multiplication and division method
- Bitwise XOR method
- Time and space complexity
- Comparison of all approaches
- Common interview mistakes
- Frequently asked interview follow-up questions
- Key takeaways
Approach 2 — Swap Without a Temporary Variable (Addition & Subtraction)
One of the most common interview follow-up questions is:
Can you swap two numbers without using a third variable?
Yes.
One approach is to use addition and subtraction.
Logic
Initially
A = 10
B = 20
Step 1
A = A + B
A = 30
Step 2
B = A - B
B = 30 - 20
B = 10
Step 3
A = A - B
A = 30 - 10
A = 20
Final
A = 20
B = 10
Java Program
public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a + b;
b = a - b;
a = a - b;
System.out.println("A = " + a);
System.out.println("B = " + b);
}
}
Output
A = 20
B = 10
Dry Run
| Step | A | B |
|---|---|---|
| Initial | 10 | 20 |
| A=A+B | 30 | 20 |
| B=A-B | 30 | 10 |
| A=A-B | 20 | 10 |
Drawback
This approach may cause integer overflow.
Example
A = 2,000,000,000
B = 2,000,000,000
Adding them exceeds the maximum value of an int.
Therefore,
this approach is not recommended for production applications.
Approach 3 — Swap Using Multiplication & Division
Another approach is to use multiplication and division.
Logic
Initial
A = 10
B = 20
Step 1
A = A × B
A = 200
Step 2
B = A ÷ B
B = 10
Step 3
A = A ÷ B
A = 20
Java Program
public class SwapUsingMultiplication {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a * b;
b = a / b;
a = a / b;
System.out.println("A = " + a);
System.out.println("B = " + b);
}
}
Output
A = 20
B = 10
Drawbacks
This approach has two major limitations.
Division by Zero
If
A = 10
B = 0
then
a = a * b;
becomes
0
and later
b = a / b;
causes
ArithmeticException
Integer Overflow
Large numbers may overflow during multiplication.
Because of these limitations,
this approach is rarely recommended.
Approach 4 — Swap Using XOR Operator
This is a favorite interview question because it demonstrates knowledge of bitwise operators.
XOR Rules
A XOR A = 0
A XOR 0 = A
These properties allow swapping without extra memory.
Logic
Initially
A = 10
B = 20
Step 1
a = a ^ b;
Step 2
b = a ^ b;
Step 3
a = a ^ b;
The values are swapped successfully.
Java Program
public class SwapUsingXOR {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("A = " + a);
System.out.println("B = " + b);
}
}
Output
A = 20
B = 10
Time Complexity
All approaches perform a constant number of operations.
| Approach | Time Complexity |
|---|---|
| Temporary Variable | O(1) |
| Addition & Subtraction | O(1) |
| Multiplication & Division | O(1) |
| XOR | O(1) |
Space Complexity
| Approach | Space Complexity |
|---|---|
| Temporary Variable | O(1) |
| Addition & Subtraction | O(1) |
| Multiplication & Division | O(1) |
| XOR | O(1) |
Comparison of All Approaches
| Approach | Extra Variable | Overflow Risk | Division by Zero | Readable | Recommended |
|---|---|---|---|---|---|
| Temporary Variable | ✅ Yes | ❌ No | ❌ No | ⭐⭐⭐⭐⭐ | ✅ Best |
| Addition & Subtraction | ❌ No | ✅ Yes | ❌ No | ⭐⭐⭐⭐ | Good for Interviews |
| Multiplication & Division | ❌ No | ✅ Yes | ✅ Yes | ⭐⭐⭐ | Not Recommended |
| XOR Operator | ❌ No | ❌ No | ❌ No | ⭐⭐ | Advanced Interview Question |
Common Mistakes
Mistake 1
Overwriting a variable before saving its value.
Wrong
a = b;
b = a;
Output
A = 20
B = 20
The original value of A is lost.
Mistake 2
Ignoring integer overflow in the addition approach.
Always remember
a = a + b;
may exceed the maximum range of an int.
Mistake 3
Using multiplication when one value is zero.
Example
A = 10
B = 0
This causes division by zero later.
Mistake 4
Using XOR without understanding it.
Interviewers may ask:
Explain how XOR swapping works.
Always be prepared to explain the bitwise logic.
Mistake 5
Choosing a clever solution over a readable one.
In production code,
clarity is usually preferred over clever tricks.
The temporary variable approach is often the best choice.
Interview Follow-up Questions
Q1. Swap two numbers without using a temporary variable.
Q2. Swap three numbers in a circular manner.
Q3. Swap two strings in Java.
Q4. Swap two array elements.
Q5. Swap two linked list nodes.
Q6. Swap first and last digits of a number.
Q7. Swap odd and even positions in an array.
Q8. Explain XOR swapping with an example.
Q9. Which swapping technique is safest for production code?
Q10. Compare all swapping techniques.
Related Coding Problems
- Reverse Integer
- Reverse String
- Swap First and Last Digit
- Palindrome Number
- Reverse Array
- Rotate Array
- Reverse Linked List
- XOR Operations
Key Takeaways
- Swapping means exchanging the values of two variables.
- The temporary variable approach is the simplest, safest, and most readable solution.
- Addition and subtraction eliminate the extra variable but may cause integer overflow.
- Multiplication and division work only when neither value is zero and may also overflow.
- XOR swapping avoids overflow from arithmetic operations and does not require extra memory, but it is less readable.
- Every swapping technique shown runs in O(1) time and uses O(1) extra space.
Interview Tip
If an interviewer asks:
"Write a Java program to swap two numbers."
Start with the temporary variable approach because it is the most readable and maintainable. Once you've solved it, mention that the same problem can also be solved using addition/subtraction, multiplication/division, and bitwise XOR. Then explain the trade-offs—especially integer overflow and readability. Demonstrating both the straightforward solution and its alternatives shows strong problem-solving skills and practical engineering judgment.