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

TuanhdotnetTuanhdotnet
4 min read

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

2.2 Breaking Down the Code

Step 1: Combining Strings

str1 = str1 + str2;

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());

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());

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

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 more at : Ways to Swap Two Strings in Java Without Using Built-In Functions

0
Subscribe to my newsletter

Read articles from Tuanhdotnet directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tuanhdotnet
Tuanhdotnet

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.