Working with Text Blocks (Java 15+)

1. Creating Text Blocks

SyntaxDetail
Open""" + newline (mandatory)
Close"""
TypeString (interned)
CompileSame as concatenated string literal

Example: Basic block

String json = """
        {"name":"Alice","age":30}
        """;

2. Understanding Indentation

RuleDetail
Incidental whitespaceRemoved (common leading)
Significant whitespaceAnchored by closing """
Re-indentString.indent(n)
StripString.stripIndent()

3. Using Escape Sequences (\s, \)

EscapeEffect
\sSingle space (preserves trailing)
\ at line endSuppress newline (line continuation)
\n \tStandard escapes work
\"\"\"Embed triple-quote

4. Formatting Text Blocks

MethodUse
"%s".formatted(arg) Java 15+Instance form
String.format(template, args)Static
Template StringsPREVIEW in newer JDKs

5. Using Text Blocks for JSON

Example: JSON template

String body = """
        {
          "user": "%s",
          "ts": %d
        }""".formatted(name, System.currentTimeMillis());
BenefitNote
ReadableNo \" escaping
InterpolationUse 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 > ?
        """;
TipReason
Use prepared statementsSQL injection
Trailing newlineAids logging readability

7. Using Text Blocks for HTML

PatternUse
Static templateEmbedded HTML literal
Combine with formatInject values via formatted
Escape user inputAlways sanitize before embedding

8. Understanding Trailing Whitespace

RuleBehavior
DefaultTrailing spaces stripped per line
\sPreserves single trailing space
TabsTreated as whitespace, also stripped

9. Combining Text Blocks with String Methods

MethodUse
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);
TipWhy
No XML escaping needed in literalEmbed raw markup
XML-escape user dataPrevent injection

11. Understanding Text Block Compilation

PhaseBehavior
LexTokenized as multi-line literal
Indent stripCommon prefix removed at compile time
ResultSingle String constant in pool
ConcatAllowed: """...""" + var