Sub topic 8
How Indentation Is Stripped
This chapter assumes you can already write a basic text block with """ delimiters and understand that a text block is an ordinary String. Here you will learn the exact rule the compiler uses to decide which leading spaces are removed and which are kept. You need JDK 15 or later to run the examples.
Why Text Blocks Strip Indentation
Source code is indented to make it readable. Without stripping, a text block nested inside a method and a class would carry that indentation into the string, and a JSON document would start with 16 spaces on every line.
The compiler therefore separates two kinds of whitespace:
- Incidental whitespace is indentation that exists only to line the text block up with the surrounding code. It is removed.
- Essential whitespace is indentation that is part of the content, such as the two spaces before
"name"in a JSON object. It is kept.
The compiler does not guess. It applies a fixed algorithm, and once you know it, you can predict the result exactly.
The Algorithm
The Java Language Specification describes the processing in a fixed order. These steps run at compile time, so the stored string constant is already stripped.
- Line endings are normalized to a single line feed (
\n), whatever the source file uses. - The content is split into lines. The content starts on the line after the opening
""". Nothing except whitespace may follow the opening delimiter on its own line. - The compiler finds the significant lines. These are all non-blank lines, plus the last line (the one holding the closing
"""), even if that last line is blank. - For each significant line, it counts the leading whitespace characters. The smallest count is the minimum indentation.
- That many leading characters are removed from every non-blank line. Blank lines become empty.
- Trailing whitespace is removed from every line.
- Only now are escape sequences such as
\n,\t,\sand\"translated.
Two points in this list cause most of the surprises. The closing delimiter line takes part in step 3, and escapes are interpreted last, in step 7.
The Closing Delimiter Sets the Floor
Because the last line is always significant, the position of the closing """ can lower the minimum indentation. It can never raise it. The following program shows three placements. The show helper prints spaces as . and line ends as $ so you can see the exact content.
public class IndentDemo {
static void show(String label, String s) {
System.out.println(label + ":");
System.out.println(s.replace(' ', '.').replace("\n", "$\n"));
}
public static void main(String[] args) {
String a = """
{
"name": "Ada"
}
""";
String b = """
{
"name": "Ada"
}
""";
String c = """
{
"name": "Ada"
}""";
show("a", a);
show("b", b);
show("c", c);
}
}The output is:
a:
{$
.."name":."Ada"$
}$
b:
....{$
......"name":."Ada"$
....}$
c:
{$
.."name":."Ada"$
}Each case follows from the algorithm:
- Case a. The closing delimiter has 16 spaces of indentation, the same as
{and}. The minimum is 16, so all 16 are removed. The text keeps its relative indentation (two spaces before"name") and ends with a line feed, because the closing delimiter sits on its own line. - Case b. The closing delimiter has only 12 spaces. The minimum drops to 12, so each content line keeps 4 extra spaces. This is the main tool for deliberately keeping indentation.
- Case c. The closing delimiter follows
}on the same line. That line is now a content line with 16 spaces of indentation. The result has no trailing line feed.
| Closing delimiter position | Effect on content |
|---|---|
| Same indentation as the least-indented content line | All incidental indentation removed, trailing line feed added |
| Further left than all content | Extra indentation kept on every line, trailing line feed added |
| Further right than all content | No effect on indentation, trailing line feed added |
| At the end of the last content line | Indentation by content only, no trailing line feed |
Relative Indentation Is Preserved
The algorithm subtracts the same number of characters from every line. Lines that are indented more than the minimum keep the difference. That is why nested structures such as JSON, YAML, SQL subqueries and HTML survive intact:
String yaml = """
server:
port: 8080
tls:
enabled: true
""";
System.out.print(yaml);The least-indented line is server:, so its 8 spaces are removed. port keeps 2 spaces and enabled keeps 4. The printed text is valid YAML starting at column 0.
Blank Lines and Trailing Whitespace
Blank lines are not significant, with one exception: the last line. A blank line in the middle of a text block, even one that contains no indentation at all, does not pull the minimum down to zero:
String s = """
first
second
""";
System.out.print(s);The empty line has zero leading characters, but it is skipped when the minimum is computed. The minimum is 8, taken from first and second. The string is "first\n\nsecond\n".
Trailing whitespace is a separate matter. Every line loses its trailing spaces and tabs (step 6). This is deliberate, because trailing spaces are invisible in an editor and often added or removed by tooling. If you need a significant trailing space, you must write it as an escape such as \s, which is interpreted after the stripping. The next chapter covers escapes in detail.
Reproducing the Algorithm with stripIndent
The String.stripIndent() method (added in Java 15) applies steps 1 to 6 to any string. This lets you experiment without recompiling a text block, and lets you normalize text that did not come from a literal, such as a text read from a file. Escapes are not touched.
public class StripDemo {
static void show(String label, String s) {
System.out.println(label + ":");
System.out.println(s.replace(' ', '.').replace("\n", "$\n"));
}
public static void main(String[] args) {
String raw = " one \n\n two \n ";
show("blank and trailing", raw.stripIndent());
String mixed = "\tfoo\n bar";
show("tab vs spaces", mixed.stripIndent());
}
}The output is:
blank and trailing:
one$
..two$
tab vs spaces:
foo$
...barIn the first example the last line contains only 4 spaces. It counts as significant, so the minimum is 4. It then becomes an empty line, which is why the result ends with a line feed. The trailing spaces after one and two are removed. The empty line in the middle was skipped when the minimum was computed.
The second example shows the most common trap, covered next.
Tabs and Spaces Count the Same
The algorithm counts characters, not columns. A tab and a space each count as one character of indentation. In mixed above, the first line has one tab and the second has four spaces. The minimum is 1, so one character is removed from each line. The tab disappears completely, and the spaces line keeps three spaces.
If a text block mixes tabs and spaces, the result depends on character counts rather than how the lines look in your editor. Two lines can look aligned and still strip differently. Use one kind of whitespace consistently in text blocks. Most projects use spaces. Some compilers and linters can flag mixed indentation.
Escapes Do Not Count as Indentation
Escape sequences are interpreted after stripping (step 7). This has two consequences.
- A
\tor\sat the start of a line is not whitespace to the algorithm. It is a backslash and a letter. It does not affect the minimum indentation, and it is not removed. - An escape can therefore protect whitespace from being stripped.
\sat the end of a line turns into a space after trailing whitespace was already trimmed, so the space survives.
String t = """
name:\tAda
city:\tLondon
""";
System.out.print(t);Both lines have 8 spaces of source indentation, which are removed. The \t sequences become real tab characters afterward, so the output contains a tab between the label and the value.
Common Errors
- Text after the opening delimiter.
String s = """Hello""";does not compile. The opening"""must be followed by a line terminator, with only optional whitespace between them. - A closing delimiter that is too far left. A stray
"""at column 0 sets the minimum indentation to 0 and keeps all the source indentation. This usually happens after an automatic reformat. Check the closing delimiter first when a text block has unexpected leading spaces. - Expecting a trailing newline in case c. If the closing delimiter is on the last content line, the string has no final
\n. Comparisons withequalsfail when the expected value does have one. - Mixed tabs and spaces. See the previous section. The result depends on character counts.
- Relying on trailing spaces. They are always removed. Use
\swhere a trailing space is part of the content.
Summary
The compiler computes a minimum indentation from all non-blank lines and the closing delimiter line, removes that many characters from each line, trims trailing whitespace, and only then interprets escapes. The closing delimiter's position is the control you use to keep or remove indentation. stripIndent() runs the same stripping on any string, which makes it a convenient way to check your predictions.
Exercise
A text block has three content lines indented by 12, 16 and 12 spaces. The closing delimiter is on its own line indented by 8 spaces. How many leading spaces does each content line have in the resulting string, and does the string end with a line feed?
Show answer
The minimum indentation is 8, because the closing delimiter line is significant and has the smallest count. Each line loses 8 spaces, so the lines have 4, 8 and 4 leading spaces. The string ends with a line feed, because the closing delimiter is on its own line.
Exercise
What does this code print, and why? Describe the exact string content.
String s = """
a
b\tc
""";
System.out.print(s);
Assume that the line containing b has three trailing spaces after \tc in the source.
Show answer
It prints a, then a line with two leading spaces, b, a tab character and c, each followed by a line feed. The minimum indentation is 8, so 8 spaces are removed from both lines, leaving 2 spaces before b. The three trailing spaces are removed in the trailing whitespace step. The \t is turned into a tab only after stripping, so it does not count as indentation and is kept.
Exercise
A teammate sees that a text block's lines all start with 4 unexpected spaces. The content lines are indented 12 spaces and the closing delimiter is indented 8 spaces. Give two different fixes, and say what each one changes.
Show answer
Move the closing delimiter to 12 spaces, so the minimum indentation becomes 12 and all of the leading spaces are removed. Alternatively, call stripIndent() on the result. That would not help here, because the string is already stripped by the compiler and has a minimum of 4, but calling stripIndent() on the result does remove the remaining 4 spaces, since the new minimum is 4. The first fix changes the literal and costs nothing at run time. The second keeps the literal and does extra work each time the line runs.