SoFunction
Updated on 2025-05-17

How to efficiently build strings in Java

In Java programming, string operations are an indispensable part of daily development. However, due to Java'sStringClasses are immutable, and new objects are created every time a string is modified (such as concatenation or replacement), which can cause efficiency issues in performance-sensitive scenarios. For this purpose, Java providesStringBuilderClass, which is a variable character sequence designed for efficient construction and modification of strings.

Key points

  • EfficiencyStringBuilderProvides an efficient way to build and modify strings, especially suitable for multiple string operations in a loop.
  • Variability: With immutableStringdifferent,StringBuilderAllows modifications on the same object to reduce memory overhead.
  • Non-thread safeStringBuilderSuitable for single-threaded environments; for multi-threaded scenarios, thread-safe should be usedStringBuffer
  • Smooth APIStringBuilderSupports chain calls to make the code more concise and easy to read.
  • Widely used: From simple string splicing (such as generating comma-separated lists) to complex string operations,StringBuilderAll are ideal choices.

What is StringBuilder?

StringBuilderYes JavaA class in the package that creates and manipulates variable character sequences. andStringCompared with immutability of classes,StringBuilderAllows to modify its contents directly without creating new objects.

This makes it significant performance advantages in scenarios where string modifications are required (such as looping splicing or dynamically constructing text).

andStringBuilderSomething similarStringBuffer, but the latter is thread-safe, and the method is processed synchronously, so in a single threaded environment,StringBuilderMore popular because of its lower overhead.

Why do I need a StringBuilder?

Java'sStringClasses are immutable, and there are several reasons:

  • Security: Immutable objects do not need synchronization in a multi-threaded environment and are suitable as keys for hash tables.
  • Performance optimization: String constants can be cached (such as string pools) to improve memory utilization.
  • Thread safety: Immutability ensures that strings behave predictably in concurrent scenarios.

However, immutability also presents challenges.

For example, use+When the operator performs string concatenation, a new operation will be created.StringObject.

In a loop, this method will lead to the creation of a large number of temporary objects, increasing the burden of memory and garbage collection.StringBuilderThis problem is solved by providing a variable character buffer.

How to use StringBuilder?

Basic usage

Create aStringBuilderThe object is very simple:

StringBuilder sb = new StringBuilder();

Availableappend()Methods add content, supporting multiple data types (such as strings, numbers, characters, etc.):

("Hello");
(", ");
("World");

passtoString()Method converts the result toString

String result = ();
(result); // Output: Hello, World

Efficiency Advantages

use+When the operator is concatenated with strings, the compiler implicitly creates aStringBuilderObject. For example:

String s = "Hello" + ", " + "World";

Will be compiled as:

String s = new StringBuilder().append("Hello").append(", ").append("World").toString();

However, use directly in loops+Operators can cause performance problems:

String s = "";
for (int i = 0; i < 1000; i++) {
    s += i; // Create a new StringBuilder every loop}

A better approach is to use it explicitlyStringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    (i);
}
String s = ();

This way only creates oneStringBuilderObjects, significantly improve efficiency.

Advanced Methods

StringBuilderThere are several ways to manipulate string content:

method describe Example
append(Object obj) Add content to the end ("text")
insert(int offset, String str) Insert content at the specified location (5, " World")
delete(int start, int end) Delete characters in the specified range (0, 6)
replace(int start, int end, String str) Replace characters in the specified range (0, 5, "Universe")
reverse() Invert character sequence ()

Here is a comprehensive example:

StringBuilder sb = new StringBuilder("Hello");
(5, " World"); // Hello World
(0, 6);        // World
(0, 5, "Universe"); // Universe
();           // esrevinU
(()); // Output: esrevinU

Smooth API style

StringBuilderHow to modify (e.g.append()insert()etc.) ReturnStringBuilderThe object itself supports chained calls. This "smooth API" style makes the code more concise:

String result = new StringBuilder()
    .append("Hello")
    .append(", ")
    .append("World")
    .toString();
(result); // Hello, World

This method not only improves the readability of the code, but also reduces the use of temporary variables.

Practical example: Building a comma-separated list

A common task is to convert arrays or lists into comma-separated strings while avoiding redundant commas at the end. useStringBuilderIt can be easily achieved:

String[] words = {"apple", "banana", "cherry"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ; i++) {
    if (i > 0) {
        (", ");
    }
    (words[i]);
}
String result = ();
(result); // apple, banana, cherry

In Java 8 and above,()A simpler alternative is provided:

String result = (", ", words);
(result); // apple, banana, cherry

Although()More concise, butStringBuilderMore flexible when more complex logic is needed (such as dynamic conditional stitching).

StringBuilder vs. StringBuffer

StringBuilderandStringBufferThe functions are similar, but there are the following differences:

characteristic StringBuilder StringBuffer
Thread safety Non-thread safe Thread safety (method synchronization)
performance Faster, suitable for single threading Slightly slow, because of synchronization overhead
Introduce time Java 5 Java 1.0

In single-threaded environments, it is recommended to useStringBuilderfor better performance. In a multi-threaded environment, if thread safety is required, you should chooseStringBuffer

Related string processing technology

Character-by-character string processing

Sometimes characters in strings need to be processed one by one. Here are a few methods:

  1. usecharAt()
String str = "Hello";
for (int i = 0; i < (); i++) {
    ((i));
}
  1. usetoCharArray()
String str = "Hello";
for (char ch : ()) {
    (ch);
}
  1. usechars()(Java 8+)
String str = "Hello";
().forEach(c -> ((char) c));

Align and indent strings

  • use(): Suitable for simple left or right alignment:
("%-10s %10s%n", "Left", "Right");
// Output: Left            Right
  • Java 12'sindent()method: Add or remove leading spaces for multi-line strings:
String text = "Line1\nLine2\nLine3";
((4));
// Output://     Line1
//     Line2
//     Line3
  • Java 12'sstripIndent()method: Remove common leading spaces for each line in a multi-line string:
String input = """
        The following:
           Volume 1
           Volume 4
              4A
              4B""";
(());
// Output:// The following:
//    Volume 1
//    Volume 4
//       4A
//       4B

Best Practices

  • Choose the right tool: Used in loops or complex string operationsStringBuilder;For a small number of static connections, use+operator or()
  • Initial capacity: If you predict the length of the string, you can construct itStringBuilderSpecify the initial capacity (such asnew StringBuilder(100)) to reduce the overhead of internal array expansion.
  • Thread safety: In a multi-threaded environment, useStringBufferOr protected by synchronization mechanismStringBuilder
  • Code readability: Write concise code with a smooth API style, but avoid over-chained calls that cause debugging difficulties.

References

  • Java StringBuilder Class Documentation
  • GeeksforGeeks: Java StringBuilder Class

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.