Swap Two Numbers in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Basics

What You’ll Learn

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.

Temp Variable

Classic

Save, overwrite, restore.

Arithmetic Swap

No named temp

Add / subtract exchange (watch overflow).

XOR Trick

Integers

Interview curiosity, not style.

No Data Loss

Order

Save before you overwrite.

Live Preview

Try 5 & 10

Swap custom integers instantly.

O(1)

All variants

Constant time and space.

Introduction

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.

Why it matters?

Swap is a building block for sorting, partitioning, and many in-place algorithms.

Key Highlights

Save First

temp holds a copy.

Preferred

temp is safest.

XOR Caveat

Integers only.

Equal OK

7, 7 stays 7, 7.

In short: exchange values without losing either — prefer a temp variable in Java.

📝 Problem & Approach

Given two variables, exchange their values so each holds what the other used to hold.

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

Inputs & Outputs

ItemTypeDescription
a, bany / intValues to exchange (XOR needs ints).
Resultsame typesa holds old b; b holds old a.
tempsame as aOptional holding spot.

Minimal workflow

Pseudocode
temp = a
a = b
b = temp

Method comparison

MethodIdeaNotes
Temp variableSave, overwrite, restoreUniversal across languages
Arithmetica = a + b; b = a - b; a = a - bNo named temp; overflow risk
XORa ^= b; b ^= a; a ^= bIntegers; interview trick

⚡ Quick Reference

GoalPattern
Temp savetemp = a
Overwritea = b
Restoreb = temp
Arithmetica = a + b; b = a - b; a = a - b
XOR (ints)a ^= b; b ^= a; a ^= b
Equal valuesSwap still correct; no visible change

📋 Temp vs Arithmetic vs XOR

Same result — different packaging.

Temp
temp = a

Clearest cross-language idea

Arithmetic
a = a + b

No named temp; watch overflow

XOR
a ^= b

Integers only; less readable

Wrong
a = b first

Loses the old a

Context

When This Problem Shows Up

Reach for a swap whenever two values need to trade places in place.

  1. Interview basics

    First assignment / memory drill.

  2. Sorting steps

    Bubble / selection / partition swaps.

  3. Array elements

    temp = arr[i]; arr[i] = arr[j]; arr[j] = temp

  4. Cross-language interviews

    Temp swap proves shared concepts.

  5. Not for XOR on floats

    Stick to temp then.

Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.

🔮 Live Preview

Enter two integers and swap them with a temporary variable.

Two integers in JavaScript safe integer range.

Live result
Press “Swap”.

Examples Gallery

Three complete Java programs — temp variable, arithmetic without temp, and XOR for integers. Click View Output to reveal sample console results.

📚 Getting Started

The classic three-step swap that works in almost every language.

Example 1 — Swap Using Temp Variable

Save the first value, overwrite it, then restore into the second variable.

java
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);
    }
}

How It Works

temp keeps 5 while num1 becomes 10. Then num2 receives the saved 5.

⚡ Without a Named Temp

Arithmetic encodes both values in one variable, then peels them apart.

Example 2 — Swap Using Arithmetic

No named temp, but large values can overflow int. Prefer temp in real code.

java
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);
    }
}

How It Works

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.

Example 3 — Swap Without Temp (XOR Trick)

Works for integers. Prefer a temp variable in real Java code; keep XOR as an interview curiosity.

java
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);
    }
}

How It Works

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.

🧠 How the Temp Swap Works

1

temp = a

Save the first value.

Hold
2

a = b

Copy the second into the first.

Overwrite
3

b = temp

Restore the saved value into b.

Restore
=

Values exchanged

Neither original was lost.

🔎 Worked Walkthrough — 5 and 10

Follow the temp variable through each assignment.

Stepabtemp
start510
temp = a5105
a = b10105
b = temp1055

If you assign a = b first without saving, the original 5 disappears.

Use Cases

Where swaps show up beyond the interview prompt.

1. Interview Warm-ups

Assignment and memory basics.

Example: temp swap of 5, 10.

2. Sorting Algorithms

Bubble and selection swaps.

Example: adjacent pairs.

3. List Elements

arr[i], arr[j] = arr[j], arr[i]

Example: in-place reorder.

4. Partition Steps

Quicksort-style exchanges.

Example: pivot swaps.

5. Teaching Memory

Why overwrite order matters.

Example: walkthrough table.

6. Next: Triangular

Continue the interview chain.

Example: related CTA.

Pro Tip: say “save before overwrite” before you write the three lines.

Advantages

Why learning all three approaches is useful.

  1. 1. Temp Is Portable

    Same idea in C, Java, JS, and more.

  2. 2. Temp Is Readable

    Three clear steps, hard to get wrong in Java.

  3. 3. Constant Cost

    O(1) time and space for all variants.

  4. 4. XOR Shows Bit Tricks

    Useful trivia once you know the readable form.

Pro Tip: lead with temp; mention arithmetic or XOR only if asked about “without a temp”.

Usage Tips

Small habits that keep swap solutions interview-ready.

  1. 1. Save Before Overwrite

    Never a = b as the first step alone.

  2. 2. Prefer Temp in Java

    Clearest and safest for production and interviews.

  3. 3. Print Before and After

    Makes demos and debugging clearer.

  4. 4. Keep XOR Optional

    Integers only; mention readability cost.

  5. 5. Test Equals

    7, 7 should remain 7, 7.

Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.

Common Pitfalls

Mistakes that commonly break swap programs.

  1. 1. Overwriting Too Soon

    Writing a = b without saving a.

    → Use a temp variable.

  2. 2. XOR on Non-Integers

    Floats and strings do not XOR.

    → Use a temp variable instead.

  3. 3. Incomplete XOR Chain

    Missing one of the three ^= steps.

    → Prefer a temp variable in Java.

  4. 4. Thinking Equals Is Broken

    Expecting failure when a == b.

    → Swap is still correct.

  5. 5. Forcing XOR in Production

    Clever but harder to maintain.

    → Use the readable form.

Edge Cases

Handle these before claiming the swap is complete.

Same values

No visible change

Swap is still correct.

XOR caveat

Integers only

Temp swap is preferred in Java.

Negatives

Temp / arithmetic OK

-4 and 20 swap fine.

Zeros

Valid

0, 3 becomes 3, 0.

Strings / floats

Use temp

Skip XOR.

Array indices

Same pattern

temp = arr[i]; arr[i] = arr[j]; arr[j] = temp

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Sorting building block. Almost every in-place sort swaps elements.
  • Temp is the default. Save, overwrite, restore — clear and safe.
  • XOR is optional trivia. Prefer readability unless asked specifically.
  • All variants are O(1). Cost does not grow with the numbers’ magnitude.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Temp swap 5, 10

  • Reproduce Example 1
  • Expect 10, 5

2. Arithmetic swap

  • Use add / subtract
  • Same result

3. Equal values

  • Swap 7, 7
  • Confirm still 7, 7

4. Array indices

  • Swap arr[0] and arr[1]
  • Use a temp

Notes

  • Core idea: exchange values without losing either one.
  • Java-preferred: a temporary variable.
  • XOR: mainly an interview trick for integers.
  • All swap variants are constant-time and constant extra space.

Quick Takeaway: save before overwrite — prefer a temp variable in Java.

⏱️ Time and Space Complexity

VersionTimeExtra space
Temp swapO(1)O(1)
Arithmetic swapO(1)O(1)
XOR swapO(1)O(1)

Swapping two variables does a fixed number of assignments regardless of the values.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Save before overwrite
  • Prefer a temp variable in Java
  • Print before and after
  • Know the temp pattern
  • Test equal values

❌ Don’t

  • Assign a = b first alone
  • XOR floats or strings
  • Skip readability for cleverness
  • Assume equals breaks swap
  • Ignore overflow on arithmetic swap

Key Takeaways

Knowledge Unlocked

Five things to remember about swapping

Exchange values safely — then use the idea in sorting.

5
Core concepts
+ 02

Arithmetic

a = a + b; ...

No temp
^ 03

XOR

ints only

Trick
= 04

Equals

still correct

Edge
O 05

Cost

O(1)

Analysis

❓ Frequently Asked Questions

After swapping, the first variable stores the old value of the second, and the second stores the old value of the first.
Not always. You can use arithmetic (a = a + b; b = a - b; a = a - b) or XOR, but temp is clearest and safest.
It teaches the core memory idea, avoids overflow, and works similarly across many languages.
Yes for integers, but it is less readable than a temp variable, so it is mostly an interview trick.
Swap still works; values remain the same.
Yes. Temp and arithmetic work for any ints; XOR is for integers only.
All common swap variants are O(1) time and O(1) extra space.
Show temp first, then briefly mention arithmetic or XOR if asked about swapping without a temp.

Did you Know? 🔊

Swapping values is one of the smallest building blocks in sorting. In Java, a temporary variable is the clearest and safest everyday approach.

Continue to Fibonacci Series

Learn how to generate the Fibonacci series in Java.

Fibonacci series tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful