Sub topic 3
How Indentation Is Stripped
Assume you know Java variables, loops, String, and the + operator. Text blocks require JDK 15 or later.
How Indentation Is Stripped
A text block removes common leading whitespace from its content. Java uses the closing delimiter to help determine that indentation. The delimiter is not part of the string.
String message = """
first line
second line
""";
System.out.print(message);The result is:
first line
second lineEight spaces were removed from each line. The extra two spaces on the second line remain. The string also ends with a newline because the closing delimiter is on its own line.
Escapes in Text Blocks
Quotes usually need no escaping inside a text block. These quotes become ordinary characters:
String json = """
{"name": "Ada"}
""";A backslash at the end of a source line joins the lines without adding a newline:
String line = """
This is one \
long line.
""";
System.out.print(line); // This is one long line.Use \s to preserve a trailing space. Without it, trailing spaces can be removed during text block processing.
Useful String Methods
formatted fills placeholders in a text block. stripIndent removes common indentation from an existing string, and translateEscapes converts escape sequences stored as text.
String greeting = """
Hello, %s!
You have %d messages.
""".formatted("Ada", 3);
String escaped = "\\n".translateEscapes();
System.out.print(escaped); // prints a line breakChoosing the Right Tool
| Task | Suitable tool |
|---|---|
| A few fixed values | `+` or `formatted` |
| Repeated construction in a loop | `StringBuilder` |
| Joining existing strings | `String.join` |
| Readable fixed multi-line content | Text block |
Choose the simplest tool that matches the job. Use StringBuilder when a loop repeatedly changes one result. Use a text block when layout is part of the source.
Exercise
What does """ \n A\n B\n """ contain after indentation stripping?
Show answer
It contains A, then a newline, then two spaces followed by B, and then a final newline.