Temp Variable
Classic
Save, overwrite, restore.
Swapping exchanges two variables so each holds the other’s old value: a=5, b=10 becomes a=10, b=5. You will use a temp variable, an arithmetic no-temp swap, and an optional XOR trick for integers — plus a live preview and worked examples.
Classic
Save, overwrite, restore.
No named temp
Add / subtract exchange (watch overflow).
Integers
Interview curiosity, not style.
Order
Save before you overwrite.
Try 5 & 10
Swap custom integers instantly.
All variants
Constant time and space.
Swapping means exchanging the values of two variables without losing either one. If you write a = b first, the old a is gone forever — that is why beginners learn a temporary holder.
In Java you can also swap without a named temp using arithmetic or XOR, but a temporary variable is clearest and safest. Interviews still like the classic three-step swap because it transfers across languages and sorting algorithms.
Swap is a building block for sorting, partitioning, and many in-place algorithms.
temp holds a copy.
temp is safest.
Integers only.
7, 7 stays 7, 7.
In short: exchange values without losing either — prefer a temp variable in Java.
Given two variables, exchange their values so each holds what the other used to hold.
// Before: a = 5, b = 10
// After: a = 10, b = 5 | Item | Type | Description |
|---|---|---|
a, b | any / int | Values to exchange (XOR needs ints). |
| Result | same types | a holds old b; b holds old a. |
temp | same as a | Optional holding spot. |
temp = a
a = b
b = temp | Method | Idea | Notes |
|---|---|---|
| Temp variable | Save, overwrite, restore | Universal across languages |
| Arithmetic | a = a + b; b = a - b; a = a - b | No named temp; overflow risk |
| XOR | a ^= b; b ^= a; a ^= b | Integers; interview trick |
| Goal | Pattern |
|---|---|
| Temp save | temp = a |
| Overwrite | a = b |
| Restore | b = temp |
| Arithmetic | a = a + b; b = a - b; a = a - b |
| XOR (ints) | a ^= b; b ^= a; a ^= b |
| Equal values | Swap still correct; no visible change |
Same result — different packaging.
temp = aClearest cross-language idea
a = a + bNo named temp; watch overflow
a ^= bIntegers only; less readable
a = b firstLoses the old a
Reach for a swap whenever two values need to trade places in place.
First assignment / memory drill.
Bubble / selection / partition swaps.
temp = arr[i]; arr[i] = arr[j]; arr[j] = temp
Temp swap proves shared concepts.
Stick to temp then.
Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.
Enter two integers and swap them with a temporary variable.
Three complete Java programs — temp variable, arithmetic without temp, and XOR for integers. Click View Output to reveal sample console results.
The classic three-step swap that works in almost every language.
Save the first value, overwrite it, then restore into the second variable.
public class SwapTemp {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
}
} temp keeps 5 while num1 becomes 10. Then num2 receives the saved 5.
Arithmetic encodes both values in one variable, then peels them apart.
No named temp, but large values can overflow int. Prefer temp in real code.
public class SwapArithmetic {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
}
} After num1 = num1 + num2, the sum holds both originals. Subtracting peels out the old values in reverse order. Watch for overflow when values are near Integer.MAX_VALUE.
Works for integers. Prefer a temp variable in real Java code; keep XOR as an interview curiosity.
public class SwapXor {
public static void main(String[] args) {
int a = 5;
int b = 10;
if (a != b) {
a ^= b;
b ^= a;
a ^= b;
}
System.out.println("After swapping: a = " + a + ", b = " + b);
}
} Three XOR steps rearrange the bit patterns so a and b trade places. The a != b guard avoids a known edge when both aliases point at the same location in some languages; for plain Java ints it is still a good habit to mention.
Save the first value.
Copy the second into the first.
Restore the saved value into b.
Neither original was lost.
Follow the temp variable through each assignment.
| Step | a | b | temp |
|---|---|---|---|
| start | 5 | 10 | — |
| temp = a | 5 | 10 | 5 |
| a = b | 10 | 10 | 5 |
| b = temp | 10 | 5 | 5 |
If you assign a = b first without saving, the original 5 disappears.
Where swaps show up beyond the interview prompt.
Assignment and memory basics.
Example: temp swap of 5, 10.
Bubble and selection swaps.
Example: adjacent pairs.
arr[i], arr[j] = arr[j], arr[i]
Example: in-place reorder.
Quicksort-style exchanges.
Example: pivot swaps.
Why overwrite order matters.
Example: walkthrough table.
Continue the interview chain.
Example: related CTA.
Pro Tip: say “save before overwrite” before you write the three lines.
Why learning all three approaches is useful.
Same idea in C, Java, JS, and more.
Three clear steps, hard to get wrong in Java.
O(1) time and space for all variants.
Useful trivia once you know the readable form.
Pro Tip: lead with temp; mention arithmetic or XOR only if asked about “without a temp”.
Small habits that keep swap solutions interview-ready.
Never a = b as the first step alone.
Clearest and safest for production and interviews.
Makes demos and debugging clearer.
Integers only; mention readability cost.
7, 7 should remain 7, 7.
Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.
Mistakes that commonly break swap programs.
Writing a = b without saving a.
→ Use a temp variable.
Floats and strings do not XOR.
→ Use a temp variable instead.
Missing one of the three ^= steps.
→ Prefer a temp variable in Java.
Expecting failure when a == b.
→ Swap is still correct.
Clever but harder to maintain.
→ Use the readable form.
Handle these before claiming the swap is complete.
Swap is still correct.
Temp swap is preferred in Java.
-4 and 20 swap fine.
0, 3 becomes 3, 0.
Skip XOR.
temp = arr[i]; arr[i] = arr[j]; arr[j] = temp
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: save before overwrite — prefer a temp variable in Java.
| Version | Time | Extra space |
|---|---|---|
| Temp swap | O(1) | O(1) |
| Arithmetic swap | O(1) | O(1) |
| XOR swap | O(1) | O(1) |
Swapping two variables does a fixed number of assignments regardless of the values.
Swapping exchanges two values without losing either one. Learn the temp-variable pattern first, mention arithmetic or XOR only if asked, and treat XOR as optional trivia.
Practice the three examples above, then continue to the Fibonacci series.
Save first — prefer a temp variable.
Exchange values safely — then use the idea in sorting.
save / set / restore
Classica = a + b; ...
No tempints only
Trickstill correct
EdgeO(1)
AnalysisSwapping values is one of the smallest building blocks in sorting. In Java, a temporary variable is the clearest and safest everyday approach.
Learn how to generate the Fibonacci series in Java.
8 people found this page helpful