TechByteByByte

Swap Two Strings With and Without a Temp Variable - Java

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

#Strings#Basics#Easy#Java

Category: Easy | Concepts used: String references, string concatenation, substring parsing, reference vs value allocation


Problem Statement

Given two strings a and b, swap their values.

Input : a = "cat", b = "dog"     Output: a = "dog", b = "cat"
Input : a = "", b = "hi"          Output: a = "hi", b = ""

Examples (with edge scenarios)

#a (before)b (before)a (after)b (after)Note
1"cat""dog""dog""cat"Typical strings
2"""hi""hi"""Empty string check
3"same""same""same""same"Identical values
4null"hi""hi"nullNull-safety reference check

โš ๏ธ Common Beginner Mistake

MistakeImpactFix
Trying arithmetic operators on stringsCompile-time syntax errorUse string references or concatenation techniques
Assuming concatenation-based swaps are fasterExtremely slow and memory-intensive due to String immutabilityUse the temporary variable approach for standard code

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.

Analogy: Labeling Folders

Imagine you have two folders on your desk:

  • Folder A is labeled โ€œCatโ€ and contains documents.
  • Folder B is labeled โ€œDogโ€ and contains documents.

Swapping them:

  • Solution 1 (Reference Swap): You simply swap the labels on the folders. The folders themselves donโ€™t move; you just swap the label pointers. This is instant and takes no physical effort.
  • Solution 2 (Concatenation and Slicing): Instead of swapping labels, you take the documents from both folders, staple them together into one giant stack (concatenation), place them in Folder A, and then use scissors to cut them apart (substrings) to separate the papers back into the respective folders. This takes much more work, wastes paper, and is highly prone to mistakes!

This is the standard, production-ready solution in Java.

Intuition

In Java, strings are objects, and string variables are references (pointers) to locations in the heap memory (String Pool). When we swap them using a temporary variable, we are only swapping the references, not copying the actual text data. This runs in constant (O(1)) time.

public class SwapStringsWithTemp {
    public static void main(String[] args) {
        String a = "cat", b = "dog";
        System.out.println("Before: a=" + a + ", b=" + b);

String temp = a; // temp now references "cat"
        a = b;            // a now references "dog"
        b = temp;         // b now references "cat"

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

Output:

Before: a=cat, b=dog
After: a=dog, b=cat

Solution 2 โ€” Concatenation & Slicing, No Temp Variable

This approach swaps strings without using a temporary variable, using concatenation.

Intuition

By appending b to a, we create a single combined string ("catdog"). We can then use indices and lengths to extract the original segments back into b and a.

public class SwapStringsNoTemp {
    public static void main(String[] args) {
        String a = "cat", b = "dog";
        System.out.println("Before: a=" + a + ", b=" + b);

a = a + b; // a becomes "catdog"

        // Extract original a into b: substring from 0 to (length of "catdog" - length of "dog")
        b = a.substring(0, a.length() - b.length()); // b becomes "cat"

        // Extract original b into a: substring starting from length of b ("cat") to the end
        a = a.substring(b.length()); // a becomes "dog"

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

Output:

Before: a=cat, b=dog
After: a=dog, b=cat

๐Ÿ“Š Visual Sequence Diagram

sequenceDiagram
    participant a as Variable A ("cat")
    participant b as Variable B ("dog")
    Note over a, b: Concatenation Swap (No Temp Variable)
    a->>a: Step 1: Concatenate (a = a + b -> "catdog")
    b->>b: Step 2: Slice head (b = a.substring(0, len(a) - len(b)) -> "cat")
    a->>a: Step 3: Slice tail (a = a.substring(len(b)) -> "dog")
    Note over a, b: After Swap: a = "dog", b = "cat"

Interviewer Insights

This question highlights the difference between primitive data types and heap objects.

Follow-up questions you might get:

  • โ€œWhat are the performance implications of Solution 2?โ€ โ†’ Solution 2 is highly inefficient. In Java, String objects are immutable. When we perform a = a + b, Java creates a new String in memory. When we call substring(), more string objects are allocated. This takes (O(N+M)) time and space. Conversely, Solution 1 only swaps 64-bit reference pointers in the stack, taking (O(1)) time with zero extra heap allocations.
  • โ€œWhat if one of the strings is null?โ€ โ†’ Solution 1 handles it safely. Solution 2 will throw a NullPointerException when trying to call .length() or .substring() on a null reference. Always mention this null vulnerability of the concatenation approach.

Quick Recap

ApproachHeap AllocationTime ComplexityNull SafetyInterview Signal
Temp VariableNone (reference pointer swap)(O(1))YesStandard, production-grade, highly efficient
Concatenation / SubstringHigh (creates multiple new String objects)(O(N+M))No (throws NPE)Demonstrates puzzle solving, but carries performance bottlenecks
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed