Sub topic 10
Text Blocks with `formatted`, `stripIndent` and `translateEscapes`
This chapter assumes you know basic Java syntax, the String class, method calls, and text-block delimiters. Text blocks require JDK 15 or later. A text block is still an ordinary String; these methods create and return other String values rather than changing the original.
Formatting a Text Block
Use String.formatted when a multi-line string contains values that should be inserted at runtime. The method uses the same formatting rules as String.format.
Placeholders begin with %. Common placeholders include:
%sfor a string or another object%dfor an integer%ffor a floating-point value%nfor the platform's line separator
The arguments appear in the same order as the placeholders.
public class TextBlockToolsDemo {
public static void main(String[] args) {
String name = "Ada";
int unread = 3;
String message = """
Hello, %s!
You have %d new messages.
""".formatted(name, unread);
System.out.print(message);
}
}The resulting string is:
Hello, Ada!
You have 3 new messages.The closing delimiter still contributes a final line break in this example. The call to formatted happens after the compiler creates the text-block String.
You can use indexed arguments when you need to reuse or reorder a value:
String label = "%2$s scored %1$d points.".formatted(95, "Mina");
System.out.println(label); // Mina scored 95 points.A formatting error, such as using %d with a non-number, causes an exception at runtime. Keep the placeholder type consistent with the supplied argument.
Removing Indentation with `stripIndent`
String.stripIndent() removes common leading whitespace from every nonblank line. It is useful for a string assembled from several sources or for text whose indentation is not already controlled by a text-block delimiter.
String html = """
<ul>
<li>First</li>
<li>Second</li>
</ul>
""";
System.out.print(html.stripIndent());For a text block, Java already removes incidental indentation during compilation. Therefore, calling stripIndent() immediately on a carefully written text block often changes nothing. It becomes useful when the value contains additional indentation or when the value was built at runtime.
stripIndent does not change the original string. Since String is immutable, it returns a new string when changes are needed.
Converting Escaped Text with `translateEscapes`
Text blocks process escape sequences while the source code is compiled. Sometimes you instead receive escape sequences as ordinary characters at runtime. For example, a configuration value might contain the two characters \ and n, intending them to represent a line break.
translateEscapes() converts recognized Java escape sequences in a string:
String encoded = "First line\\nSecond line\\t(done)";
String decoded = encoded.translateEscapes();
System.out.print(decoded);The output is:
First line
Second line (done)The source text uses \\n because the first backslash escapes the second one in the Java string literal. At runtime, encoded contains \n. translateEscapes() then converts that sequence to a line-feed character.
It recognizes escapes such as \n, \t, \r, \f, \b, \\, \', and \". An invalid escape sequence causes IllegalArgumentException. Do not use this method on untrusted text unless you are prepared to handle that exception.
Combining the Methods
These methods can be chained because each one returns a String. Use the order that matches the transformation you need.
String report = """
Report for %s
Status: %s
Notes: %s
""".formatted("Ada", "ready", "Line one\\nLine two")
.stripIndent()
.translateEscapes();
System.out.print(report);The formatted values are inserted first. Then common indentation is removed. Finally, the \n characters inside the Notes value become a line break.
| Method | Main purpose | Returns |
|---|---|---|
| `formatted` | Inserts values into `%` placeholders | A formatted `String` |
| `stripIndent` | Removes common leading whitespace | A whitespace-adjusted `String` |
| `translateEscapes` | Converts runtime escape sequences | A decoded `String` |
Choosing the Right Transformation
Use formatted when the text is a template with changing values. Use stripIndent when indentation comes from the way text was assembled rather than from the desired output. Use translateEscapes when the input contains visible escape sequences that should become control characters.
Do not confuse a source escape with a runtime escape. In "\\n", Java creates a string containing a backslash followed by n. In "\n", Java creates a string containing an actual line break.
Exercise
What does this code print, and why? String value = "A\\nB"; System.out.print(value.translateEscapes());
Show answer
It prints A, then a line break, then B. The source \\n creates the runtime characters \n, and translateEscapes() converts them into a line-feed character.