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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
