Text Blocks in Java — Multi-Line Strings, Incidental Whitespace, Escape Tricks
Fast recall
Quick revision
Core answer
"""). They eliminate the noise of \n and + concatenation when embedding SQL, JSON, HTML, or any multi-line text in Java. The defining feature is incidental whitespace stripping: the compiler determines a common indentation prefix — usually the indentation of the closing `"""` — and removes that many leading spaces from every line. So your text block visually aligns with surrounding Java code, but the resulting string has no leading indentation. The opening """ must be followed by a line terminator (you can't put text on the opening line). Inside, double quotes don't need escaping (only """ itself does, and only if it appears literally), and backslash escapes still work. Two special escapes are unique to text blocks: `\String.format — great for templating values into a text block. Text blocks are not interpolated (Java's string templates JEP was withdrawn); to inject values you use formatted or string concatenation. The win: SQL queries, JSON payloads, HTML snippets, and GraphQL queries become readable as their natural form. The major use case in real codebases is @Query annotations in Spring Data and JSON test fixtures.Whether the candidate knows the triple-quote syntax, the incidental-whitespace stripping rule, the line-continuation `\<newline>` and `\s` escapes, and how to interpolate values via `formatted`
Putting text on the opening `"""` line (compile error). Forgetting that closing `"""` position controls indentation. Trying to use `${...}` interpolation (not supported — string templates JEP was withdrawn)
Mention `\s` for preserving trailing whitespace, `\` line continuation, the difference between `String.format` and `String.formatted`, and that string templates were withdrawn (so use `formatted` instead)
Interview-ready guide
Interview answer
Text blocks (Java 15, JEP 378) are multi-line string literals delimited by triple quotes ("""). They eliminate the noise of \n and + concatenation when embedding SQL, JSON, HTML, or any multi-line text.
Syntax basics
- Opening
"""must be followed by a newline — no text on the same line - Closing
"""on its own line OR at end of last line - Position of closing
"""determines indentation stripping
Incidental whitespace stripping — the crucial rule
- Compiler finds the common minimum leading-whitespace prefix across all lines
- Strips that many leading spaces from each line
- Closing
"""indentation participates in the calculation - Result: text aligns visually with Java code, but has no extra leading indent in the string
Quoting inside
- Single
"doesn't need escaping - Only
"""itself needs escaping (rare)
Two unique escapes
`\
- Joins next line without a newline in the result
- Useful for very long URLs or single-line SQL clauses you want wrapped in source
`\s` — literal space, preserves trailing whitespace
- Per-line trailing whitespace is auto-stripped
\sopts back in:"red \s"keeps the spaces
Standard escapes still work: \n, \t, \\, \u00XX
Result always uses LF (`\n`)
- Regardless of source file line endings
- For Windows endings in output, use
formattedor replace explicitly
No string interpolation — use `formatted`
${...}is literal in text blocks — no expansion- String templates JEP was withdrawn (design concerns)
- Use `String.formatted(args...)` (Java 15) — fluent inline alternative to
String.format - Same format spec; reads naturally chained off the text block
- For complex templating, use Mustache/FreeMarker/Pebble — not text blocks + concat
Companion String methods (Java 11–15)
isBlank()— empty or whitespace-onlystrip(),stripLeading(),stripTrailing()— Unicode-aware trimrepeat(n)— repeat the string n timeslines()— stream of linesindent(n)— add/remove leading spacesstripIndent(),translateEscapes()— lower-level for runtime text-block processingformatted(args)— fluent format
Best uses
- SQL queries (especially
@Queryannotations in Spring Data) - JSON / XML / GraphQL test fixtures
- HTML snippets in templates
- Multi-line error messages
- Embedded scripts (Bash, JavaScript) in code
Don't use for
- Single-line strings — use regular literals
- User-facing UI text — use ResourceBundle or i18n libraries
- Anything where dedicated templating libraries fit better
Common gotchas
1. Text on opening line — compile error
""" hello """— doesn't compile
2. Trailing whitespace silently stripped
- 'hello \n' becomes 'hello\n'
- Use
\sif you need them preserved
3. Indentation drift after IDE reformatting
- Review autoformatter changes
- Use
// @formatter:offif necessary
4. Line endings always LF
- For Windows line endings in output, replace or format explicitly
5. No interpolation
- Use
.formatted(args)for value injection
Performance
- Compile-time concatenation — same bytecode as old
+joins formattedmild overhead vs raw concat — usually negligible
Recommendation: Use text blocks as your default for any multi-line string — SQL queries, JSON payloads, HTML snippets, GraphQL queries, multi-line error messages. The most common real-world use is `@Query` annotations in Spring Data and JSON test fixtures. Place the closing `"""` at the same indentation as your surrounding Java (usually 8 spaces in for a method body) — this controls the strip and gives you visual alignment with code without leading indent in the string. Remember: trailing whitespace per line is auto-stripped — use `\s` if you need it preserved (rare). Use `\String.format that chains naturally off the text block. Java does NOT have string interpolation — the templates JEP was withdrawn over safety/design concerns; don't expect ${name} to work. Pair text blocks with the String API additions (isBlank, strip, lines, repeat, indent) for complete multi-line text handling. The mental model: text blocks are like Heredoc in Bash or triple-quoted strings in Python — same idea, with Java's incidental-whitespace twist for clean alignment with surrounding code.
Text Blocks in Java — Multi-Line Strings, Incidental Whitespace, Escape Tricks
Direct Answer
Text blocks (Java 15, JEP 378, preview in 13–14) are multi-line string literals delimited by triple quotes ("""). They eliminate the noise of \n and + concatenation when embedding SQL, JSON, HTML, or any multi-line text in Java. The defining feature is incidental whitespace stripping: the compiler determines a common indentation prefix — usually the indentation of the closing """ — and removes that many leading spaces from every line. So your text block visually aligns with surrounding Java code, but the resulting string has no leading indentation. The opening """ must be followed by a line terminator (you can't put text on the opening line). Inside, double quotes don't need escaping (only """ itself does, and only if it appears literally), and backslash escapes still work. Two special escapes are unique to text blocks: \<newline> (line continuation — join the next line without a newline) and \s (literal space, useful to preserve trailing whitespace which would otherwise be stripped). You can also use String.formatted(args...) (Java 15) as a fluent inline alternative to String.format — great for templating values into a text block. Text blocks are not interpolated (Java's string templates JEP was withdrawn); to inject values you use formatted or string concatenation. The win: SQL queries, JSON payloads, HTML snippets, and GraphQL queries become readable as their natural form. The major use case in real codebases is @Query annotations in Spring Data and JSON test fixtures.
Common Mistakes & Pitfalls
Putting text on the opening """ line (compile error). Forgetting that closing """ position controls indentation. Trying to use ${...} interpolation (not supported — string templates JEP was withdrawn)
Check your understanding
Answer these without looking back at the article.
- How does incidental whitespace stripping work in text blocks?
- What's the purpose of `\s` in a text block?
- How do you interpolate values into a text block?
- Why was the string templates JEP withdrawn?
- What's the difference between `String.format` and `String.formatted`?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.