Fundamentals 7 min read

Java Basics: Using StringBuilder for Efficient Mutable Strings

The article explains why Java's immutable String class can waste memory when concatenated, introduces the mutable StringBuilder class introduced in J2SE 5.0, demonstrates its usage with code examples comparing memory behavior, shows its length and capacity methods, and illustrates practical operations such as reverse and conversion between String and StringBuilder.

Lisa Notes
Lisa Notes
Lisa Notes
Java Basics: Using StringBuilder for Efficient Mutable Strings

Java's String class is immutable; each concatenation creates a new object, leaving the original in memory and potentially causing wasteful memory consumption. To address this, Java provides the mutable StringBuilder class. java.lang.StringBuilder has been available since J2SE 5.0. It starts with a default capacity of 16 characters, can be instantiated with a custom capacity, and automatically expands as needed, allowing in‑place modifications.

Example comparing String concatenation with StringBuilder:

public class StringAndStringBuilder {
    public static void main(String[] args) {
        // Allocate memory for text1
        String text1 = new String("java");
        // Allocate new memory for text2 by concatenation
        String text2 = text1 + 'c';
        // Allocate memory for builder1
        StringBuilder builder1 = new StringBuilder("java");
        // Append character c to the original builder
        StringBuilder builder2 = builder1.append('c');
        System.out.println(text1 + " " + text2);
        System.out.println(builder1 + " " + builder2);
    }
}

Running the program prints:

java java
javac javac

Memory‑usage diagrams (shown in the accompanying images) illustrate that String objects remain unchanged while StringBuilder objects are modified in place, highlighting the advantage of mutability for frequent string updates.

The class provides length‑related methods such as length(), capacity(), ensureCapacity(int), and trimToSize(). A table of these methods is displayed in the article (see image).

Commonly used operations include append(), insert(), delete(), reverse(), and conversion methods. The article shows a table of typical methods (image).

Conversion between String and StringBuilder is straightforward: builder.toString() yields a String, and the constructor new StringBuilder(String) creates a builder from a string.

To reverse a poem using plain String, the article first converts the string to a character array, swaps indices, and builds a new string:

public class PoemsExportation {
    public static void main(String[] args) {
        String s = "大江东去,浪淘尽,千古风流人物";
        int length = s.length();
        char[] arr1 = new char[length];
        char[] arr2 = new char[length];
        for (int i = 0; i < length; i++) {
            arr1[i] = s.charAt(i);
        }
        for (int j = 0; j < length; j++) {
            arr2[j] = arr1[length - 1 - j];
        }
        String result = new String(arr2);
        System.out.println(s);
        System.out.println(result);
    }
}

The output is the original line and its reversed form. Using StringBuilder, the same task becomes simpler:

public class PomesExportationImprovement {
    public static void main(String[] args) {
        String str = "大江东去,浪淘尽,千古风流人物";
        StringBuilder builder = new StringBuilder(str);
        builder.reverse();
        System.out.println(str);
        System.out.println(builder);
    }
}

Running this program yields the identical reversed line, demonstrating that StringBuilder.reverse() provides a concise, readable solution.

Overall, the article shows that for scenarios requiring frequent string modifications, the mutable StringBuilder class is preferable to immutable String concatenation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMemoryManagementCodeExampleStringBuilderMutableStringStringManipulation
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.