Swap Two Numbers Using a Third Variable in Java
Problem
Swapping two variables means exchanging their values, so each ends up holding what the other used to have.
Given two integers, swap their values using a temporary third variable.
Java Program
public class SwapUsingThirdVariable {
public static void main(String[] args) {
int a = 5;
int b = 10;
int temp = a; // save a's value before it's overwritten
a = b;
b = temp;
System.out.println("a=" + a + ", b=" + b);
}
}Output
Core Logic
A temporary variable holds one value safely while it's overwritten, so nothing is lost during the exchange.
- 1
temp = asavesa's original value (5) before it gets overwritten. - 2
a = bcopiesb's value (10) intoa, overwritinga's original 5. - 3
b = tempcopies the saved original value (5) fromtempintob, completing the swap.
temp becomes 5, then a becomes 10, then b becomes 5 — ending at a=10, b=5.Key Point: Without temp, the line a = b would overwrite a's value before it's ever saved, permanently losing the original number.
Key Concepts
Approach 2: Swap Using a Helper Method
public class SwapUsingMethod {
static void swap(int[] values) {
int temp = values[0];
values[0] = values[1];
values[1] = temp;
}
public static void main(String[] args) {
int[] values = {5, 10};
swap(values); // shared array, so the change is visible here too
System.out.println("a=" + values[0] + ", b=" + values[1]);
}
}
Output
Core Logic
Java passes primitive int arguments by value, so a method can't swap two plain int parameters directly — wrapping them in an array lets a helper method mutate shared storage instead.
- 1The two values are stored in a shared
int[]array instead of separate variables. - 2
swap(values)receives a reference to that same array, not a copy of its contents. - 3Inside
swap, the same temp-variable technique swapsvalues[0]andvalues[1]— and because the array is shared, the change is visible back inmain.
swap({5, 10}) mutates the array in place, so after the call values[0] is 10 and values[1] is 5.Key Point: This is why swap helper methods in Java take arrays, lists, or wrapper objects instead of plain int parameters — a swap(int a, int b) method would have no effect outside its own scope.
Key Concepts
Interview Questions
Why does a swap need a temporary variable?
Assigning a = b overwrites a's original value, so it must be saved first or it's lost.
Can a method swap two int arguments?
No. Java passes primitives by value, so a method only swaps its own copies. Return the values, or swap elements inside an array.