Java / Java 21 Interview Questions
What are Text Blocks in Java and how do you use them?
Text Blocks (JEP 378, finalised in Java 15) provide a multi-line string literal that preserves formatting without escape sequences. They are delimited by """ and the content starts on the line after the opening delimiter.
// Traditional string — escape-heavy
String json = "{\n" +
" \"name\": \"Alice\",\n" +
" \"age\": 30\n" +
"}";
// Text block — same result, readable
String json = """
{
"name": "Alice",
"age": 30
}
""";
// Indentation is stripped automatically:
// Java strips the minimum leading whitespace (re-indentation)
// based on the position of the closing triple quote.
// SQL example
String sql = """
SELECT id, name
FROM customers
WHERE active = true
ORDER BY name
""";
// Escape sequences still work inside text blocks
String noTrailingNewline = """
Hello\
World""";
// Backslash at end of line joins the next line — no newline inserted
// \s — a space that prevents trailing whitespace stripping
String aligned = """
one \s
two \s
""";Re-indentation rules: Java finds the minimum indentation of all non-blank content lines plus the closing delimiter line, and strips that many leading spaces from every line. Placing the closing """ at the start of the line preserves all indentation of the content; indenting it further strips more.
More Related questions...