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

Swap Two Numbers Without Third Variable in Java

beginner·  Basics & I/O  ·  Variables

Problem

Two numbers can be swapped without any extra storage by temporarily combining their values, then separating them back out.

Given two integers, swap their values without using a third variable.

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

Java Program

Java
public class SwapWithoutThirdVariable { public static void main(String[] args) { int a = 5; int b = 10; a = a + b; // a now holds the combined sum b = a - b; // b becomes a's original value a = a - b; // a becomes b's original value System.out.println("a=" + a + ", b=" + b); } }

Output

a=10, b=5

Core Logic

Addition and subtraction can swap two values without any extra variable, by temporarily storing both values' combined sum in one of them.

How It Works
  1. 1a = a + b stores the combined sum (15) in a, so a now holds both original values added together.
  2. 2b = a - b subtracts the original b (10) from that sum (15), leaving b with a's original value (5).
  3. 3a = a - b subtracts the new b (5) from the sum (15), leaving a with b's original value (10).
Starting with a=5, b=10: a becomes 15, then b becomes 5, then a becomes 10 — ending at a=10, b=5.
💡

Key Point: This trick can silently overflow if a + b exceeds int's range — for values close to Integer.MAX_VALUE, the temp-variable approach is the safer choice.

Key Concepts

arithmetic swapint overflow

Approach 2: Swap Using XOR

Java
public class SwapUsingXor { public static void main(String[] args) { int a = 5; int b = 10; a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("a=" + a + ", b=" + b); } }

Output

a=10, b=5

Core Logic

The bitwise XOR operator can swap two integers without any overflow risk, using the fact that XOR-ing a value with itself cancels it out.

How It Works
  1. 1a = a ^ b combines both original values into a using bitwise XOR.
  2. 2b = a ^ b XORs that combined value with the original b, which cancels out b's own bits and leaves a's original value in b.
  3. 3a = a ^ b XORs the combined value with the new b (a's original value), which cancels those bits out and leaves b's original value in a.
Starting with a=5 (0101), b=10 (1010): a becomes 15 (1111), then b becomes 5, then a becomes 10 — ending at a=10, b=5.
💡

Key Point: Unlike the addition/subtraction trick, XOR swap never overflows since it operates on bits directly — but it silently fails if a and b are the same variable (not just equal values), zeroing both out.

Key Concepts

XOR operatorbitwise operations

Related Programs