Text blocks (""", Java 15+)
A text block is a multi-line string literal with automatic incidental whitespace stripping: the
common leading whitespace shared by every line (determined by the closing """'s indentation) gets
removed, so you can indent the literal to match your code without that indentation ending up in the string.
The result is character-for-character identical to the equivalent manually-escaped, concatenated string --
verified below, not just asserted.
String html = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";
System.out.println(html);
String oldWay = "<html>\n" +
" <body>\n" +
" <p>Hello, world</p>\n" +
" </body>\n" +
"</html>\n";
System.out.println("identical content to the text block above: " + html.equals(oldWay));
A trailing backslash suppresses the line break (continues the same line), and \""" escapes a literal triple-quote without ending the block:
String withEscapes = """
line one \
still line one (backslash suppresses the newline)
literal quote: \"""
""";
System.out.println(withEscapes);
Text blocks compose naturally with String.formatted(...), which reads much better than concatenating a multi-line template piece by piece:
String withValues = """
Name: %s
Age: %d""".formatted("Ada", 36);
System.out.println(withValues);