Text Blocks
TL;DR
- Text Blocks (finalized in Java 15) allow you to write multi-line String literals without painful escape sequences and concatenation.
- They are defined using three double quotes:
""". - The compiler automatically strips away incidental leading whitespace (indentation).
Concept
Before Java 15, embedding a block of HTML, JSON, or a SQL query inside a Java file was a nightmare.
You had to add \n at the end of every line, wrap every line in quotes "", use + to concatenate them, and if the JSON contained its own quotes, you had to escape them with \".
Text Blocks solve this. By opening a string with """ (followed by a newline), you can paste raw, unescaped, multi-line text directly into your source code. The Java compiler intelligently looks at the indentation of the closing """ and automatically removes that baseline indentation from every line, ensuring your Strings don’t have 20 spaces of padding at the front just because they were nested inside a method.
Examples
public class TextBlockDemo {
public static void main(String[] args) {
// THE OLD WAY (Painful)
String oldJson = "{\n" +
" \"name\": \"Alice\",\n" +
" \"age\": 30\n" +
"}";
// THE NEW WAY (Text Blocks)
// You don't need to escape the inner double quotes!
// The compiler sees the closing """ is indented by 8 spaces,
// so it strips exactly 8 spaces from the start of every line.
String newJson = """
{
"name": "Alice",
"age": 30
}
""";
// Using the formatted() method (modern String.format)
String html = """
<html>
<body>
<h1>Welcome %s!</h1>
</body>
</html>
""".formatted("Bob");
}
}
Interview Questions
Q: Can you put the opening text on the same line as the """?
A: No. The Java language specification strictly requires that the opening """ must be followed by a line terminator (a newline). You cannot write String s = """Hello""";. It must be formatted across multiple lines. The compiler ignores that very first mandatory newline when constructing the final String.
Q: What do the \ and \s escape sequences do in Text Blocks?
A: - \ (Line Continuation): If you place a backslash at the very end of a line in a Text Block, it suppresses the newline. This allows you to write a massive, single-line SQL query formatted cleanly across multiple lines in your source code.
\s(Explicit Space): Text Blocks automatically strip trailing whitespace at the end of lines. If you specifically need a trailing space to be preserved, you put\sat the end of the line.