Embedding JSON or SQL in Java used to mean a mess of \n and +. Text blocks
give you readable multi-line literals, and modern String methods handle the
common chores.
Multi-line literals
A text block preserves formatting and strips the common leading whitespace based on the closing delimiter.
String json = """
{
"id": %d,
"status": "active"
}
""".formatted(id);Handy String methods
strip, isBlank, lines, and repeat cover cases that used to need helpers.
" hi ".strip(); // "hi", Unicode-aware
"\n\t".isBlank(); // true
"a\nb\nc".lines().count(); // 3Takeaways
- Text blocks are ideal for SQL, JSON, and HTML snippets.
- Use
formattedto interpolate values into a block. - Prefer
stripovertrimfor correct Unicode whitespace handling.
Add a trailing \ inside a text block to suppress the newline at that line,
useful for long single-line strings you want to wrap in source.