TechByteByByte

Swap Two Numbers With and Without a Temp Variable - Java

An easy QA/automation coding interview question: swap Two Numbers With and Without a Temp Variable, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Basics#Arithmetic#Bitwise XOR#Easy#Java

Category: Easy | Concepts used: Temporary registers, arithmetic swapping, bitwise XOR operations


Problem Statement

Given two integers a and b, swap their values โ€” so a gets bโ€™s original value and b gets aโ€™s original value.

Input : a = 5, b = 10        Output: a = 10, b = 5
Input : a = -3, b = 7        Output: a = 7, b = -3

Examples (with edge scenarios)

#a (before)b (before)a (after)b (after)Note
1510105Standard positive values
20990Swapping with zero
3-377-3Swapping with negative numbers
44444Swapping identical values

โš ๏ธ Common Beginner Mistake

MistakeImpactFix
Overwriting a before backing it upa = b; b = a; leaves both variables holding bโ€™s original valueUse a temp variable to cache a before overwriting
Relying on arithmetic swap for arbitrary valuesRisk of integer overflow when a + b exceeds 2,147,483,647Use the temporary variable approach in production code

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.

Analogy: The Juice Cup Switch

Imagine you have two glasses filled with different colored juices:

  • Glass A contains Red Juice.
  • Glass B contains Blue Juice.

You want to swap the contents so Glass A has Blue Juice and Glass B has Red Juice:

  • You cannot pour Red directly into Blue because they will mix and get ruined.
  • Instead, you introduce an empty Glass Temp.
  • You pour Red from Glass A into Glass Temp. Now Glass A is empty, and Temp has Red.
  • You pour Blue from Glass B into Glass A. Now Glass B is empty, and Glass A has Blue.
  • You pour Red from Glass Temp into Glass B. Now both glasses are successfully swapped!

Solution 1 โ€” Using a Temp Variable (Simple & Safe)

This is the standard, production-ready solution.

Intuition

By using an auxiliary variable temp, we hold the value of a in a separate memory register, allowing us to safely overwrite a with b and then write the cached value into b.

public class SwapWithTemp {
    public static void main(String[] args) {
        int a = 5, b = 10;
        System.out.println("Before: a=" + a + ", b=" + b);

int temp = a; // Step 1: Copy a's original value to temp
        a = b;         // Step 2: Overwrite a with b's value
        b = temp;      // Step 3: Copy the original a from temp to b

System.out.println("After: a=" + a + ", b=" + b);
    }
}

Output:

Before: a=5, b=10
After: a=10, b=5

Solution 2 โ€” Using Arithmetic, No Temp Variable

This approach uses arithmetic addition and subtraction to track differences.

Intuition

By combining the values into a total sum, we use the sum as a memory buffer. We can retrieve the original variables by subtracting individual components.

public class SwapWithArithmetic {
    public static void main(String[] args) {
        int a = 5, b = 10;

a = a + b; // a becomes the sum of both (5 + 10 = 15)
        b = a - b; // b becomes original a (15 - 10 = 5)
        a = a - b; // a becomes original b (15 - 5 = 10)

System.out.println("After: a=" + a + ", b=" + b);
    }
}

Note on Overflow: While Java allows integer overflows silently (wrapping around), large numbers can still result in arithmetic anomalies on other systems.


Solution 3 โ€” Using Bitwise XOR (^), No Temp Variable, No Overflow

This approach performs swapping using XOR bitwise operations.

Intuition

The XOR operator has two key properties:

  1. x ^ x = 0 (XOR-ing a value with itself cancels it out)
  2. x ^ 0 = x (XOR-ing a value with zero returns the value)

By mixing the bits of a and b together using a = a ^ b, we can extract the original values selectively.

public class SwapWithXOR {
    public static void main(String[] args) {
        int a = 5, b = 10;

a = a ^ b; // a becomes the XOR combination
        b = a ^ b; // b becomes the original a (XOR-canceling out b)
        a = a ^ b; // a becomes the original b (XOR-canceling out the new b)

System.out.println("After: a=" + a + ", b=" + b);
    }
}

Dry Run (a = 5, b = 10 in binary)

a = 0101 (5)
b = 1010 (10)

Step 1: a = a ^ b = 0101 ^ 1010 = 1111 (15)
Step 2: b = a ^ b = 1111 ^ 1010 = 0101 (5)  -> b now holds the original a!
Step 3: a = a ^ b = 1111 ^ 0101 = 1010 (10) -> a now holds the original b!

๐Ÿ“Š Visual Sequence Diagram

sequenceDiagram
    participant a as Variable A
    participant b as Variable B
    participant temp as Temp Variable
    Note over a, b: Before Swap: a = 5, b = 10
    a->>temp: Step 1: Copy value of 'a' into 'temp' (temp = 5)
    b->>a: Step 2: Copy value of 'b' into 'a' (a = 10)
    temp->>b: Step 3: Copy value of 'temp' into 'b' (b = 5)
    Note over a, b: After Swap: a = 10, b = 5

Interviewer Insights

This question determines whether you understand low-level execution trade-offs and code safety.

Follow-up questions you might get:

  • โ€œWhat is the self-swap gotcha in Solution 3?โ€ โ†’ If a and b refer to the same memory location (e.g., swapping arr[i] with arr[j] when i == j):
    a = a ^ a; // a becomes 0
    a = a ^ a; // a remains 0
    a = a ^ a; // a remains 0
    This destroys the value! This is why XOR swapping is risky inside sorting loops unless guarded by if (i != j).
  • โ€œWhich solution is preferred in production code?โ€ โ†’ Solution 1 (Temp Variable). Modern CPU compilers optimize temporary variables into quick register swaps. It is also completely type-safe and handles reference variables, objects, and strings, whereas arithmetic and XOR swaps only support primitive numbers.

Quick Recap

ApproachMemory OverheadType CompatibilityRisksInterview Signal
Temp VariableMinor (1 variable)All Types (Objects, Strings, Primitives)NoneStandard, highly readable, production-grade
ArithmeticNoneNumbers OnlyInteger OverflowDemonstrates mathematical puzzle-solving
Bitwise XORNoneIntegers OnlyDestroys data on self-swapDemonstrates low-level binary register manipulation
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed