DEV Community

Anh Trần Tuấn
Anh Trần Tuấn

Posted on • Originally published at tuanh.net on

Ways to Swap Two Strings in Java Without Using Built-In Functions

1. Understanding the Challenge

Swapping two strings involves exchanging their values. While swapping primitive data types like int or double is straightforward, strings introduce complexity due to their immutable nature in Java. Immutability means a string’s value cannot be modified after creation, making the task more interesting when avoiding built-in methods.

Image

1.1 Why Avoid Built-In Functions?

Built-in functions abstract away the complexity of operations. While they are optimized and convenient, solving this problem manually improves your understanding of how strings are stored and manipulated in memory. It’s an exercise in thinking like the JVM (Java Virtual Machine).

1.2 What Happens When Swapping Strings?

Java strings are references to objects in the heap memory. When swapping, you’re manipulating these references, not the actual string content. This behavior impacts how swaps are performed and emphasizes the importance of reference understanding.

2. Step-by-Step Solution: Swapping Without Built-In Functions

The key is to use intermediate variables to hold temporary data and exchange values without breaking the immutability contract. Below is the step-by-step explanation.

2.1 The Code Example

public class StringSwap {

    public static void main(String[] args) {
        // Initialize two strings
        String str1 = "Hello";
        String str2 = "World";

        // Print initial values
        System.out.println("Before Swap:");
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);

        // Perform the swap without built-in functions
        str1 = str1 + str2; // Combine strings
        str2 = str1.substring(0, str1.length() - str2.length()); // Extract str1's original value
        str1 = str1.substring(str2.length()); // Extract str2's original value

        // Print swapped values
        System.out.println("
After Swap:");
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
    }
}
Enter fullscreen mode Exit fullscreen mode

2.2 Breaking Down the Code

Step 1: Combining Strings

str1 = str1 + str2;
Enter fullscreen mode Exit fullscreen mode

Here, the two strings are concatenated, effectively storing both values in str1. At this point:

  • str1 contains "HelloWorld"
  • str2 is unchanged.

Step 2: Extracting the Original Value of str1

str2 = str1.substring(0, str1.length() - str2.length());
Enter fullscreen mode Exit fullscreen mode

This line calculates the length of the original str1 by subtracting the length of str2 from the combined string. The result is assigned to str2, which now holds the original value of str1 ("Hello").

Step 3: Extracting the Original Value of str2

str1 = str1.substring(str2.length());
Enter fullscreen mode Exit fullscreen mode

Now, the original str2 value is extracted by skipping the length of the new str2. This leaves only the original value of str2 in str1.

3. Exploring Alternatives

While the above method uses substring, let’s consider another approach that avoids even that.

3.1 Using Character Arrays

public class StringSwapAlternative {

    public static void main(String[] args) {
        // Initialize strings
        String str1 = "Java";
        String str2 = "Programming";

        System.out.println("Before Swap:");
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);

        // Convert to character arrays
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();

        // Swap arrays
        char[] temp = arr1;
        arr1 = arr2;
        arr2 = temp;

        // Recreate strings
        str1 = new String(arr1);
        str2 = new String(arr2);

        System.out.println("
After Swap:");
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this method, strings are broken into character arrays, swapped using a temporary variable, and then reassembled. This approach avoids substring entirely but comes at the cost of extra memory allocation.

4. Lessons from the Exercise

Strings Are Immutable

The immutability of strings reinforces their reliability in concurrent programming. Swapping demonstrates how to manipulate references instead of content.

Memory Management Insights

Understanding string manipulation illuminates how Java manages heap memory and optimizes string storage using features like the String Pool.

When to Use Built-In Functions

While avoiding built-in functions is educational, in real-world scenarios, they provide efficiency and readability. Knowing what happens under the hood prepares you for optimizing critical applications.

5. Conclusion

Swapping two strings in Java without built-in functions is more than an academic exercise—it’s a gateway to understanding Java's core principles. By tackling this challenge, you enhance your skills in memory management, immutability, and problem-solving.

Do you have other creative ways to swap strings? Share your approach or ask any questions in the comments below!

Read posts more at : Ways to Swap Two Strings in Java Without Using Built-In Functions

Warp.dev image

The best coding agent. Backed by benchmarks.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay