In Java programming, string operations are an indispensable part of daily development. However, due to Java'sString
Classes 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 providesStringBuilder
Class, which is a variable character sequence designed for efficient construction and modification of strings.
Key points
-
Efficiency:
StringBuilder
Provides an efficient way to build and modify strings, especially suitable for multiple string operations in a loop. -
Variability: With immutable
String
different,StringBuilder
Allows modifications on the same object to reduce memory overhead. -
Non-thread safe:
StringBuilder
Suitable for single-threaded environments; for multi-threaded scenarios, thread-safe should be usedStringBuffer
。 -
Smooth API:
StringBuilder
Supports 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,
StringBuilder
All are ideal choices.
What is StringBuilder?
StringBuilder
Yes JavaA class in the package that creates and manipulates variable character sequences. and
String
Compared with immutability of classes,StringBuilder
Allows 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).
andStringBuilder
Something similarStringBuffer
, but the latter is thread-safe, and the method is processed synchronously, so in a single threaded environment,StringBuilder
More popular because of its lower overhead.
Why do I need a StringBuilder?
Java'sString
Classes 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.String
Object.
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.StringBuilder
This problem is solved by providing a variable character buffer.
How to use StringBuilder?
Basic usage
Create aStringBuilder
The 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 aStringBuilder
Object. 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 oneStringBuilder
Objects, significantly improve efficiency.
Advanced Methods
StringBuilder
There 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
StringBuilder
How to modify (e.g.append()
、insert()
etc.) ReturnStringBuilder
The 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. useStringBuilder
It 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, butStringBuilder
More flexible when more complex logic is needed (such as dynamic conditional stitching).
StringBuilder vs. StringBuffer
StringBuilder
andStringBuffer
The 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 useStringBuilder
for 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:
-
use
charAt()
:
String str = "Hello"; for (int i = 0; i < (); i++) { ((i)); }
-
use
toCharArray()
:
String str = "Hello"; for (char ch : ()) { (ch); }
-
use
chars()
(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's
indent()
method: Add or remove leading spaces for multi-line strings:
String text = "Line1\nLine2\nLine3"; ((4)); // Output:// Line1 // Line2 // Line3
-
Java 12's
stripIndent()
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 operations
StringBuilder
;For a small number of static connections, use+
operator or()
。 -
Initial capacity: If you predict the length of the string, you can construct it
StringBuilder
Specify the initial capacity (such asnew StringBuilder(100)
) to reduce the overhead of internal array expansion. -
Thread safety: In a multi-threaded environment, use
StringBuffer
Or 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.