A text block (Java 15) is a multi-line string literal written between triple quotes ("""). It keeps line breaks and removes the common indentation automatically, so JSON, SQL, HTML or XML can be written as they look, without \n and + concatenation.
Key Points: • The opening """ must be followed by a line break. The content starts on the next line. • Incidental indentation (the common leading spaces) is removed, based on the least-indented line and the position of the closing """. • Double quotes inside need no escaping. • \ at the end of a line joins it with the next line, and \s keeps a trailing space. • Use formatted() or String.format() to insert values. Text blocks are ordinary String objects.
Code Example:
public class TextBlockDemo {
public static void main(String[] args) {
String oldJson = "{\n" +
" \"name\": \"Asha\",\n" +
" \"role\": \"Developer\"\n" +
"}";
String json = """
{
"name": "Asha",
"role": "Developer"
}""";
System.out.println(json);
System.out.println("Same text: " + json.equals(oldJson));
String sql = """
SELECT id, name
FROM employees
WHERE salary > %d
""".formatted(50000);
System.out.print(sql);
}
}Output:
{ "name": "Asha", "role": "Developer" } Same text: true SELECT id, name FROM employees WHERE salary > 50000
Good to Know: Interviewers sometimes ask how indentation is decided. Explain that Java strips the smallest common indentation, and that moving the closing """ to the left adds indentation to every line. It's a detail that shows hands-on experience.
Interview Tip: A concise interview answer is:
"A text block is a multi-line string between triple quotes that keeps line breaks and strips common indentation. I use it for JSON, SQL and HTML so they can be written as they look, without \n and string concatenation."
Previous question: What are record patterns in Java 21?
Next question: What are sequenced collections in Java 21?