Java Tutorial
🔍
Java ProgramsBasics & I/OSwap Two Numbers Using Third Variable

Swap Two Numbers Using Third Variable in Java

beginner·  Basics & I/O  ·  Variables

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.

Input
a=5, b=10
Output
a=10, b=5

Java Program

Java
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

a=10, b=5

Core Logic

A temporary variable holds one value safely while it's overwritten, so nothing is lost during the exchange.

How It Works
  1. 1temp = a saves a's original value (5) before it gets overwritten.
  2. 2a = b copies b's value (10) into a, overwriting a's original 5.
  3. 3b = temp copies the saved original value (5) from temp into b, completing the swap.
Starting with a=5, b=10: 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

temporary variablevariable assignment

Approach 2: Swap Using a Helper Method

Java
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

a=10, b=5

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.

How It Works
  1. 1The two values are stored in a shared int[] array instead of separate variables.
  2. 2swap(values) receives a reference to that same array, not a copy of its contents.
  3. 3Inside swap, the same temp-variable technique swaps values[0] and values[1] — and because the array is shared, the change is visible back in main.
Calling 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

pass-by-valuearrayshelper method

Related Programs