The text construction consists of combining or transforming strings without creating unnecessary intermediate objects.
In the previous article we learned that String objects are immutable. Operations produce a new result instead of modifying the original object.
For simple operations, this is fine. But imagine you are reading a file with 10,000 lines and you want to join them all into a single variable.
String texto = "";
for (int i = 0; i < 10000; i++) {
texto = texto + " line " + i; // CRIME AGAINST RAM!
}On each loop iteration, Java has to copy all the accumulated text to add a little bit more. This has a complexity of O(n²). It is slow, inefficient, and can block your server.
To solve this, Java provides tools to work with mutable strings.
StringBuilder: the notebook
The java.lang.StringBuilder class is like a String but without the immutability restriction. It is a resizable character buffer.
Imagine that String is a sign engraved in stone (cannot be edited), and StringBuilder is a ring binder (you can add and remove pages whenever you want).
How to use it
The standard pattern is: create the builder, modify it at will, and finally convert it to a fixed String.
// 1. Create the Builder
StringBuilder sb = new StringBuilder();
// 2. Modify (append is super fast)
sb.append("Hello");
sb.append(" ");
sb.append("World");
// We can chain calls (Fluent API)
sb.append(" from").append(" Java");
// Other useful operations
sb.insert(5, "dear "); // Insert in the middle
sb.reverse(); // Reverse the text (dlroW olleH...)
// 3. Convert to final String
String resultado = sb.toString();When to use it?
Use StringBuilder when you accumulate text in a loop or through many successive operations. For simple concatenations, + is more readable and the compiler can optimize it through JVM concatenation mechanisms.
StringBuilder vs StringBuffer
This is the classic job interview question. Both do the same thing (mutable strings), have the same methods, and are used the same way. What is the difference?
StringBuffer(Legacy): It is the original class (Java 1.0). It is Synchronized (Thread-Safe). This means that if two threads try to write at the same time, they block to avoid overwriting each other. This safety comes at a cost: it is slow.StringBuilder(Modern): It arrived in Java 5. It is not synchronized. It is much faster.
Summary:
In single-threaded code, StringBuilder is usually preferred. StringBuffer maintains synchronized methods and can still be useful when several simple operations share the same instance, although it is often better to avoid that shared mutable state.
Modern formatting: text blocks (Java 15+)
For 25 years, writing HTML, JSON, or SQL inside a Java class was a nightmare of escaped quotes and plus signs.
// THE HORROR (Old Java)
String html = "<html>\n" +
" <body>\n" +
" <h1>Hello</h1>\n" +
" </body>\n" +
"</html>";Fortunately, since Java 15, we have Text Blocks. They are defined with three double quotes """.
// THE GLORY (Java 15+)
String html = """
<html>
<body>
<h1>Hello</h1>
</body>
</html>
""";Java is smart enough to:
- Ignore accidental indentation from the code (it aligns the text to the left based on the position of the closing quotes).
- Not require escaping of inner double quotes.
- Automatically interpret line breaks.
Injecting variables (formatted)
Text Blocks combine great with the new .formatted() method (or String.format), which works just like the printf we saw earlier.
String nombre = "Luis";
String json = """
{
"user": "%s",
"active": true
}
""".formatted(nombre);