Sub topic 2
Java StringBuilder and Text Blocks: Building and Writing Strings Efficiently
This chapter assumes you know Java loops, methods, objects, and the String class. A StringBuilder is a mutable character sequence. You can change its contents without creating a new builder.
Inserting, Deleting, Replacing and Reversing
Indexes start at zero. The end index in replace and delete is exclusive.
public class EditDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World");
sb.insert(5, "!!!"); // Hello!!!, World
sb.replace(0, 5, "Howdy"); // Howdy!!!, World
sb.delete(5, 8); // Howdy, World
sb.reverse(); // dlroW ,ydwoH
System.out.println(sb);
}
}setCharAt(index, character) changes one character. setLength(newLength) can truncate the builder or add null characters. These operations modify the same object.
Length, Capacity and Presizing
length() counts stored characters. capacity() reports the current buffer size. A builder grows automatically when its capacity is too small.
public class CapacityDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(64);
System.out.println(sb.length()); // 0
System.out.println(sb.capacity()); // 64
sb.append("abc");
System.out.println(sb.length()); // 3
}
}Presize a builder when you can estimate the final size. This can reduce buffer growth and copying, but capacity does not affect the text's correctness.
StringBuilder or StringBuffer?
Both classes build mutable strings. Their main difference is synchronization.
| Class | Typical use | Thread safety |
|---|---|---|
| StringBuilder | Local or single-threaded construction | Not synchronized |
| StringBuffer | Shared mutable text in older concurrent code | Individual methods are synchronized |
Prefer StringBuilder for ordinary code because it usually has less synchronization overhead. StringBuffer does not make a sequence of several operations atomic; shared compound operations still need coordination.
Writing Multi-Line Strings with Text Blocks
A text block is a multi-line String, available in Java 15 and later. Java removes incidental indentation based on the least-indented content and the closing delimiter.
public class TextBlockDemo {
public static void main(String[] args) {
String json = """
{
"name": "%s"
}
""".formatted("Ada");
String oneLine = """
first \
second
""";
String normalized = " one\n two\n".stripIndent();
String newline = "\\n".translateEscapes();
System.out.print(json);
System.out.print(oneLine);
System.out.print(normalized);
System.out.print(newline);
}
}The closing delimiter controls the indentation baseline. A newline before that delimiter normally becomes the final newline. A backslash at the end of a text-block line joins the next line. Use \s when a trailing space must remain. Quotes do not need escaping. formatted fills placeholders, stripIndent removes common indentation, and translateEscapes interprets escape sequences in an existing string.
Exercise
What is the final text after new StringBuilder("abcd").delete(1, 3).insert(1, "X")?
Show answer
It is aXd. delete removes b and c, leaving ad; insert then places X between a and d.