Summary

Learn how to swap two variables without using a third variable in Java. Understand step-by-step logic, Java code, and why this trick works—perfect for beginners and interview prep.

Article Body

Efficient Java Trick to Swap Two Variables Without a Temporary Variable
Efficient Java Trick to Swap Two Variables Without a Temporary Variable

Swapping two variables is a classic programming task. Typically, we use a third (temporary) variable to do this. But did you know you can swap two variables in Java without using a third variable? This trick is not just smart—it helps you optimize memory in tight coding environments and looks great in interviews.

In this article, you’ll learn how to swap two integer variables without using a third variable in Java. We’ll explain every step clearly so even a beginner can understand.


🧪 What is Variable Swapping?

Variable swapping means exchanging the values of two variables. For example:

int a = 5;
int b = 10;

After swapping:

a = 10;
b = 5;

Usually, we do this using a temporary variable. But here’s how to do it without any extra variable.


🔄 Method 1: Swap Using Addition and Subtraction

✅ Java Code Example:

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

        System.out.println("Before swapping:");
        System.out.println("a = " + a + ", b = " + b);

        // Step 1: Add both numbers and assign it to 'a'
        a = a + b;  // a becomes 15 (5 + 10)

        // Step 2: Subtract new 'a' with 'b' and assign to 'b'
        b = a - b;  // b becomes 5 (15 - 10)

        // Step 3: Subtract new 'a' with new 'b' and assign to 'a'
        a = a - b;  // a becomes 10 (15 - 5)

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

📝 Step-by-Step Explanation

✅ Step 1:

a = a + b;
  • We add a and b and store the result in a.

  • Now, a holds the total of both numbers.

  • Example: a = 5 + 10 = 15

✅ Step 2:

b = a - b;
  • We subtract original b from the new value of a.

  • This gives us the original value of a.

  • Example: b = 15 - 10 = 5

✅ Step 3:

a = a - b;
  • We subtract new b (which is old a) from new a (which is the total).

  • This gives us the original value of b.

  • Example: a = 15 - 5 = 10

Now, both variables are swapped, and we never used a third variable.


⚠️ Important Notes

  • This method works best for integers.

  • It may cause overflow if the numbers are very large, e.g., beyond the range of int in Java (-2,147,483,648 to 2,147,483,647).

  • For large number safety, consider using the XOR method below.


🔄 Method 2: Swap Using XOR (Bitwise Operator)

This is a more efficient and safer method when working with large integers.

✅ Java Code Example:

public class SwapWithXOR {
    public static void main(String[] args) {
        int a = 7;
        int b = 12;

        System.out.println("Before swapping:");
        System.out.println("a = " + a + ", b = " + b);

        // Step 1: XOR both values and store in 'a'
        a = a ^ b;  // a = 7 ^ 12

        // Step 2: XOR new 'a' with 'b' and store in 'b'
        b = a ^ b;  // b = (7 ^ 12) ^ 12 = 7

        // Step 3: XOR new 'a' with new 'b' and store in 'a'
        a = a ^ b;  // a = (7 ^ 12) ^ 7 = 12

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

📝 XOR Method Explanation

XOR (exclusive OR) is a bitwise operator:

  • 1 ^ 1 = 0

  • 0 ^ 1 = 1

  • x ^ x = 0

  • x ^ 0 = x

This method avoids the risk of overflow and is memory-safe.


🎯 When to Use These Methods?

Situation Recommended method
Small integers Addition/Subtraction
Large numbers or secure operations XOR method
Interview coding questions Either, explain both
Memory-critical apps XOR method (bit-level optimization)

✅ Output of Both Programs

Before Swapping:

a = 5, b = 10

After Swapping:

a = 10, b = 5

👨‍🏫 Why Learn This?

  • Asked frequently in coding interviews.

  • Shows deep understanding of operators and memory management.

  • Helps in optimization and low-level programming.


📌 Final Thoughts

Swapping two variables without using a third one is a smart programming trick that every Java developer should know. Whether you're preparing for an interview or just improving your coding skills, these methods will give you an edge.

Learn both Addition/Subtraction and XOR-based methods. Practice them, understand them deeply, and you’ll be ready to explain them like a pro.

Comments

TOPICS MENTIONED IN THIS ARTICLE

About the Author(s)

  • Rahul Kumar photo

    Rahul Kumar

    Software Engineer & Tech Editor

    Rahul is a software engineer and editor at Galaxy Founder, passionate about technology, startups, and digital innovation. With a keen eye for emerging trends and a love for clean, efficient code, Rahul shares insights and resources to help others navigate the evolving tech landscape.

    View all articles by Rahul Kumar

Galaxy Founder | Latest News, Job Updates & In-Depth Product Reviews — Galaxy Founder brings you the latest news, real-time job postings, and honest product reviews to keep you informed, updated, and ahead. Discover trusted content across trending topics only on Galaxy Founder.