Sub topic 10
Text Blocks with formatted, stripIndent and translateEscapes
This chapter assumes you can write a text block ("""), know how the closing delimiter controls indentation, and know the escapes \s and \<newline>. It also assumes you have used String.format or printf. You need JDK 15 or later. Every example here is a complete snippet you can paste into a main method or a small class.
A Text Block Is Just a String
A text block is a literal that the compiler turns into an ordinary java.lang.String. After compilation it has no memory of the """ delimiters, the indentation you stripped, or the escapes you wrote. So every String method works on it, including three that matter for this chapter:
| Method | Added in | What it does |
|---|---|---|
| `formatted(Object... args)` | Java 15 | Fills placeholders such as `%s` and `%d` using the same rules as `String.format` |
| `stripIndent()` | Java 15 | Removes incidental indentation, using the compiler's algorithm |
| `translateEscapes()` | Java 15 | Converts escape sequences such as `\t` in the text into the characters they stand for |
formatted is the one you will use most. stripIndent and translateEscapes matter when the text did not come from a Java literal, for example when you read a template from a file.
Filling Placeholders with formatted
formatted is an instance method, so you can call it directly on the closing delimiter of a text block. text.formatted(args) behaves exactly like String.format(text, args).
public class ReportDemo {
public static void main(String[] args) {
String template = """
Report for %s
Items: %d
Total: %8.2f
Done: %b
""";
System.out.print(template.formatted("Ada", 3, 19.5, true));
}
}The output is:
Report for Ada
Items: 3
Total: 19.50
Done: trueThe compiler strips the indentation first, so the placeholders sit at the left margin. formatted runs later, at run time, on the already-stripped string. This ordering has three consequences.
- The width in
%8.2fcounts characters of the final line. It is not affected by how deeply the literal was indented in your source. - A text block that calls
formattedis not a compile-time constant. A plain text block is a constant and can be used in an annotation argument or aswitchlabel, but the result of a method call cannot. - Argument errors appear at run time, not compile time. Too few arguments throw
MissingFormatArgumentException. A wrong type, such as%dwith aString, throwsIllegalFormatConversionException. Extra arguments are silently ignored.
Line breaks: \n or %n
Inside a text block, each line break in the source becomes \n, whatever line endings your editor uses. If you add %n to a template, formatted replaces it with the platform line separator, which is \r\n on Windows. Mixing the two gives you a string with inconsistent endings on Windows. Prefer the plain line breaks of the text block and leave %n out.
Percent signs must be doubled
Any % in the text is the start of a placeholder once you call formatted. This catches people who add formatted to an existing block of prose, HTML, or a CSS snippet.
public class PercentDemo {
public static void main(String[] args) {
String ok = """
Discount: %d%%
Width: 100%%
""".formatted(20);
System.out.print(ok);
}
}This prints Discount: 20% and Width: 100%. Without the doubled %%, the call throws a subclass of IllegalFormatException. Braces, quotes, and backslashes are not special to formatted, so JSON and code snippets work well as long as you double the percent signs.
Column alignment
A text block works well for fixed-width output because the layout you see in the source is the layout you get. Width and flag options do the alignment.
public class TableDemo {
public static void main(String[] args) {
String row = """
%-8s|%6d|%8.1f
""";
System.out.print(row.formatted("alpha", 42, 3.14159));
System.out.print(row.formatted("beta", 7, 100.0));
}
}The output is:
alpha | 42| 3.1
beta | 7| 100.0The same template string is reused for both rows. A text block assigned to a variable is a normal String, so you can call formatted on it as many times as you like.
stripIndent: The Compiler's Algorithm on Any String
When the compiler reads a text block, it does three things in order:
- It normalizes every line terminator (
\r\nor\r) to\n. - It removes incidental whitespace, which is the indentation shared by all lines.
- It interprets escape sequences.
stripIndent performs steps 1 and 2 on any string you give it. It does this by splitting the string into lines and finding the smallest indentation among the non-blank lines. The last line is always included in that count, even if it is blank. It then removes that many leading whitespace characters from every line and strips trailing whitespace from every line.
public class StripDemo {
public static void main(String[] args) {
String raw = " alpha\n beta\n gamma";
System.out.println(raw.stripIndent());
}
}The output is:
alpha
beta
gammaThe shared indentation of four spaces is removed, and the extra two spaces on beta survive because they are significant, not incidental.
The last line decides a lot
A text block's closing delimiter on its own line is what makes that line count toward the minimum. A plain string has no delimiter, so the same rule applies to whatever trails the final \n. This produces a result that surprises people.
public class LastLineDemo {
public static void main(String[] args) {
String a = " a\n b\n"; // ends with a newline, last line is empty
String b = " a\n b\n "; // last line is four spaces
System.out.println(a.stripIndent().equals(a)); // true: nothing was removed
System.out.println(b.stripIndent().equals("a\nb\n")); // true
}
}In a, the final empty line has zero indentation, so the minimum is zero and nothing is stripped. In b, the last line holds four spaces. It is a whitespace-only line, so it is cleared to empty, but it still counts toward the minimum, which stays at four. That is exactly how the closing delimiter works in a source literal. A closing """ indented to the same column as the content leaves the content stripped to the left margin. A closing """ placed further left strips less.
stripIndent also removes trailing spaces and tabs from every line. That is the reason \s exists in text blocks, and it matters again below.
translateEscapes: Interpreting Backslashes at Run Time
Suppose a template file contains the two characters \ and t. When you read the file, you get a backslash followed by a letter, not a tab. The compiler's escape step only runs on source literals, so for text that arrives at run time you call translateEscapes.
It recognizes the escapes Java allows in string literals:
\b,\t,\n,\f,\r,\s\",\',\\- octal escapes such as
\0to\377 \followed by a line terminator, which is removed along with the terminator
Any other backslash sequence throws IllegalArgumentException. Unicode escapes (\u0041) are not handled by this method. In source code they are translated very early in compilation, before any of this, and translateEscapes does not repeat that step.
Running the whole pipeline
The next program simulates what the compiler does to a text block, using a string that has literal backslashes in it, and then fills the placeholders.
public class PipelineDemo {
public static void main(String[] args) {
// Simulates text read from a file: two-space indent, backslash-t sequences
String raw = " Name:\\t%s\n Role:\\t%s";
String result = raw
.stripIndent()
.translateEscapes()
.formatted("Ada", "Engineer");
System.out.println(result);
}
}In the Java source, \\t is a backslash followed by t, which is what a file would contain. The output has two lines, and each has a real tab between the label and the value:
Name: Ada
Role: EngineerWhy the order matters
The compiler strips indentation before it translates escapes, and your code should do the same. If you reverse them, translateEscapes first turns \n into a real line break, and stripIndent then sees extra lines it was never meant to treat as separate. It also turns \s into a space before stripIndent can remove trailing whitespace, which is the one case where you might want that order. The safe sequence is:
stripIndent()translateEscapes()formatted(...)
Putting formatted last avoids a second problem. If an argument contains a backslash sequence, such as a Windows path like C:\temp, then calling translateEscapes after formatted would try to interpret it, and \t would become a tab. The arguments should go in after the escapes are resolved.
Keeping trailing spaces
Trailing whitespace is removed by stripIndent and by the compiler. To keep it, write \s at the end of the line. Because escape translation happens after stripping, the space is protected.
public class TrailingDemo {
public static void main(String[] args) {
String raw = "key =\\s\n value";
System.out.println("[" + raw.stripIndent().translateEscapes() + "]");
}
}The output is [key = followed by a line break and value], with the space after the equals sign preserved on the first line. A literal trailing space in raw would have been removed.
Choosing Between the Three
Use this as a quick guide for the methods in this chapter.
| Situation | Use |
|---|---|
| A multi-line literal with values to insert | Text block with `formatted` |
| Text read from a file whose indentation should be removed | `stripIndent` |
| Text read from a file that contains `\t`, `\n`, `\"` as written characters | `translateEscapes` |
| A template with many literal `%` characters | Concatenation, `StringBuilder`, or doubling every `%` |
| Many values in a loop | `StringBuilder`, not repeated `formatted` calls |
Common Mistakes
- Forgetting to double
%after addingformattedto an existing text block. - Passing too few arguments. The error only shows when that line of code runs.
- Calling
stripIndenton text that ends with a newline and expecting the indentation to disappear. - Calling
translateEscapeson text that holds a Windows path or a regular expression. Their backslashes are data and would be changed or rejected withIllegalArgumentException. - Using
%nin a text block and then comparing the result with a string that uses\n. The two differ on Windows.
Exercise
What does " a\n b\n".stripIndent() return, and why? How would you change the input so that the four leading spaces are removed?
Show answer
It returns the string unchanged. The text ends with \n, so the last line is empty. The empty last line counts toward the minimum indentation, which is therefore zero. To strip the four spaces, end the string with four spaces and no final newline text after them, as in " a\n b\n ". The result is "a\nb\n".
Exercise
The following code throws an exception at run time. Explain why and fix it. String s = """ Progress: %d% complete """.formatted(75);
Show answer
In formatted, the % that follows %d starts a new conversion, and % c is read as a space flag with the c conversion. That conversion needs a second argument, so the call throws an IllegalFormatException subclass. A literal percent sign must be written %%, so the fix is Progress: %d%% complete, which prints Progress: 75% complete.
Exercise
A file contains the characters Col1\tCol2 (a backslash and a t, not a tab). After reading it into a String named line, which call turns it into a tab-separated string, and why can't you use stripIndent for this?
Show answer
line.translateEscapes() converts the backslash-t sequence into a tab. stripIndent only deals with line terminators and leading and trailing whitespace. It does not interpret backslashes at all.