Working with Text Blocks (Java 15+)
1. Creating Text Blocks
| Syntax | Detail |
|---|---|
| Open | """ + newline (mandatory) |
| Close | """ |
| Type | String (interned) |
| Compile | Same as concatenated string literal |
2. Understanding Indentation
| Rule | Detail |
|---|---|
| Incidental whitespace | Removed (common leading) |
| Significant whitespace | Anchored by closing """ |
| Re-indent | String.indent(n) |
| Strip | String.stripIndent() |
3. Using Escape Sequences (\s, \)
| Escape | Effect |
|---|---|
\s | Single space (preserves trailing) |
\ at line end | Suppress newline (line continuation) |
\n \t | Standard escapes work |
\"\"\" | Embed triple-quote |
4. Formatting Text Blocks
| Method | Use |
|---|---|
"%s".formatted(arg) Java 15+ | Instance form |
String.format(template, args) | Static |
| Template Strings | PREVIEW in newer JDKs |
5. Using Text Blocks for JSON
Example: JSON template
String body = """
{
"user": "%s",
"ts": %d
}""".formatted(name, System.currentTimeMillis());
| Benefit | Note |
|---|---|
| Readable | No \" escaping |
| Interpolation | Use formatted |
6. Using Text Blocks for SQL
Example: SQL query
String sql = """
SELECT u.id, u.name
FROM users u
WHERE u.active = true
AND u.created_at > ?
""";
| Tip | Reason |
|---|---|
| Use prepared statements | SQL injection |
| Trailing newline | Aids logging readability |
7. Using Text Blocks for HTML
| Pattern | Use |
|---|---|
| Static template | Embedded HTML literal |
| Combine with format | Inject values via formatted |
| Escape user input | Always sanitize before embedding |
8. Understanding Trailing Whitespace
| Rule | Behavior |
|---|---|
| Default | Trailing spaces stripped per line |
\s | Preserves single trailing space |
| Tabs | Treated as whitespace, also stripped |
9. Combining Text Blocks with String Methods
| Method | Use |
|---|---|
lines() | Stream of lines |
stripIndent() | Drop incidental indent |
translateEscapes() | Process escapes manually |
formatted(args) | Substitute placeholders |
10. Using Text Blocks for XML Templates
Example: SOAP envelope
String envelope = """
<?xml version="1.0"?>
<Envelope>
<Body>%s</Body>
</Envelope>""".formatted(payload);
| Tip | Why |
|---|---|
| No XML escaping needed in literal | Embed raw markup |
| XML-escape user data | Prevent injection |
11. Understanding Text Block Compilation
| Phase | Behavior |
|---|---|
| Lex | Tokenized as multi-line literal |
| Indent strip | Common prefix removed at compile time |
| Result | Single String constant in pool |
| Concat | Allowed: """...""" + var |