Advertisement
Intermediate Java, Java Fundamentals: Syntax, Data Types & Operators

What is the difference between a Java text block (introduced as a standard feature in Java 15) and a traditional String literal, and what specific syntax rules govern indentation handling?

Short answer

A text block (delimited by triple double-quotes """) lets you write multi-line String literals directly in source code without needing explicit \n escape sequences or string concatenation across lines, automatically handling incidental leading whitespace stripping based on the…

Save Java mock interview
Advertisement
AModel answer
A text block (delimited by triple double-quotes """) lets you write multi-line String literals directly in source code without needing explicit \n escape sequences or string concatenation across lines, automatically handling incidental leading whitespace stripping based on the closing delimiter's own indentation (the 'minimal indentation' across all lines, including the closing delimiter's position, is stripped uniformly from every line) -- this dramatically improves readability for embedded multi-line content like JSON, SQL queries, or HTML snippets directly within Java source code, compared to the older approach of manually concatenating multiple string literals with explicit newline escapes.
// Old approach: verbose, error-prone concatenation with explicit \n
String oldJson = "{\n" +
    "  \"name\": \"Alice\",\n" +
    "  \"age\": 30\n" +
    "}";

// Modern text block: clean, readable, matches how the content actually looks
String newJson = """
    {
      "name": "Alice",
      "age": 30
    }
    """;
Real-world example
A codebase embedding SQL queries directly in Java source switches from painfully concatenated multi-line string literals (requiring manual \n and string-plus-string concatenation for every line) to text blocks, immediately improving readability and making the embedded SQL look and format almost exactly as it would in a standalone .sql file.
Likely follow-ups
  • How exactly does the text block's automatic indentation-stripping algorithm determine how much leading whitespace to remove from each line?
  • Can you still use escape sequences like \n or \" within a text block if genuinely needed?
Related topics