Modern Java Features
Text Blocks
Write multi-line string literals easily using Text Blocks introduced in Java 15.
Interview: Tests text block syntax: indentation strip rules, line terminations, and using escape characters.
Introduced in Java 15, Text Blocks provide a way to declare multi-line string literals without the need for manual escape sequences (like \n) or concatenation.
Core Idea
Text Blocks open and close with triple double-quotes ("""), preserving multi-line layouts and indentation automatically.
Why It Matters
Greatly simplifies embedding JSON, HTML, or SQL queries inside Java source code.
Interview Lens
Focuses on compiler indentation rules and stripping common incidental whitespace.
Indentation Strip Rules
The compiler calculates incidental whitespace by checking the leftmost non-whitespace characters or the position of the closing triple quotes. This shared prefix spacing is automatically stripped from the final string, allowing developers to align the text block with their code without affecting string value.
Code Walkthrough
This program demonstrates embedding formatted JSON strings using Text Blocks.
public class TextBlockDemo { public static void main(String[] args) { // Opening triple-quotes must be followed by a newline! String json = """ { "name": "Alice", "role": "Developer" } """;
System.out.print(json); } }
Interview-Relevant Information
Q: How do you prevent a newline in a text block?
Answer: Use a trailing backslash (\) at the end of a line. The compiler interprets the backslash as a line-continuation character, merging the next line without adding a newline character.
Quick Checklist
How do you open a text block? How does the compiler strip incidental spaces? If yes, you understand text blocks.
Use Cases
Embedding HTML templates inside rendering code.
Writing clean JSON request bodies in test classes.
Common Mistakes
Placing text on the same line as the opening triple-quotes (this is a compile error; the opening quotes must be followed by a newline).
Confusing incidental whitespace with intentional spacing, resulting in incorrect indentation.