Back to Java 21+ Features
Q8Question 8 of 10

What are text blocks?

Key Concepts
  • Text blocks use triple quotes to delimit multi-line string literals that preserve newlines and eliminate escape characters
  • The opening triple quote must be followed by a newline and content starts on the next line
  • Incidental leading whitespace is stripped based on the position of the closing delimiter
  • Double quotes inside text blocks do not need escaping, making JSON and SQL much cleaner
  • Use .formatted() for variable interpolation and backslash at line end to suppress newlines
  • Text blocks are compile-time sugar producing ordinary String objects with no runtime cost
  • Final in Java 15 via JEP 378

Definition

Text blocks are multi-line string literals delimited by triple quotes that preserve newlines, strip incidental whitespace, and eliminate the need to escape double quotes.
  • Syntax – opening """ followed by a newline, content on subsequent lines, closing """ controls indentation.
  • No escaping – double quotes inside the block do not need backslash escaping, so embedded JSON, SQL, and HTML read naturally.
  • Whitespace management – the compiler strips common leading whitespace (incidental indentation) based on the closing delimiter position.
  • Special escapes – \s forces a trailing space, trailing \ on a line suppresses the newline to join lines.
  • Compile-time – text blocks produce ordinary String objects; they interoperate with .formatted() for interpolation and carry no runtime cost.

Before text blocks, writing a JSON transfer payload required escaping every quote: "{\"from\": \"SAV2001\"}". With text blocks, you write the JSON exactly as it appears: """\n{"from": "SAV2001"}\n""". It is like writing on plain paper instead of filling in forms where every field needs special markup.

Understanding the Concepts

What are text blocks?

Text blocks (JEP 378, final in Java 15) are multi-line string literals delimited by triple quotes """. They remove the noise of escaped quotes and explicit \n when embedding JSON, SQL, HTML, or XML in Java code. The opening """ must be followed by a line terminator; the content starts on the next line.

JAVA
// Before text blocks: escaped quotes everywhere
String json = "{\"from\": \"SAV2001\", \"to\": \"CUR3001\", \"amount\": 50000}";

// With text blocks: clean, readable
String json = """
        {"from": "SAV2001", "to": "CUR3001", "amount": 50000}
        """;

How does indentation stripping work?

The compiler strips incidental leading whitespace based on the position of the closing """. If the closing delimiter is at column 8, then 8 spaces are stripped from every content line.

JAVA
public class StatementService {
    String query = """
            SELECT account_id, balance, holder_name
            FROM accounts
            WHERE branch = 'HDFC-MUM-001'
            ORDER BY balance DESC
            """;
    // The 12 leading spaces (matching the closing """) are stripped.
    // Result: each line starts at column 0.
}

How do you use text blocks for SQL?

JAVA
package com.bank.repository;

import java.math.BigDecimal;

public class AccountRepository {

    private static final String TRANSFER_QUERY = """
            UPDATE accounts
            SET balance = balance - ?
            WHERE account_id = ?
              AND balance >= ?
            """;

    private static final String STATEMENT_QUERY = """
            SELECT t.txn_date, t.description, t.amount, t.balance_after
            FROM transactions t
            WHERE t.account_id = ?
              AND t.txn_date BETWEEN ? AND ?
            ORDER BY t.txn_date DESC
            """;
}

How do you use text blocks for JSON?

JAVA
package com.bank.service;

import java.math.BigDecimal;

public class NotificationService {

    public String buildPayload(String from, String to, BigDecimal amount) {
        return """
                {
                    "type": "TRANSFER",
                    "from": "%s",
                    "to": "%s",
                    "amount": %s,
                    "currency": "INR"
                }
                """.formatted(from, to, amount);
    }
}
TEXT
{
    "type": "TRANSFER",
    "from": "SAV2001",
    "to": "CUR3001",
    "amount": 50000,
    "currency": "INR"
}

What special escape sequences are available?

Two escape sequences are specific to text blocks.

A trailing \ at the end of a line suppresses the newline, joining the current line with the next. This is useful for long lines that you want to wrap in source but produce a single line in the output.

The \s escape forces a trailing space. Without it, trailing spaces on a line are stripped.

JAVA
String singleLine = """
        SELECT * FROM accounts \
        WHERE branch = 'HDFC-MUM-001' \
        ORDER BY balance DESC\
        """;
// Result: "SELECT * FROM accounts WHERE branch = 'HDFC-MUM-001' ORDER BY balance DESC"
// All on one line because \ suppressed newlines

String withTrailingSpace = """
        Name: Rajesh\s
        Account: SAV2001\s
        """;
// Each line ends with a space (\s prevents stripping)

How are text blocks different from regular strings?

| Aspect | Regular String | Text Block |
|---|---|---|
| Delimiter | "..." | """...""" |
| Multi-line | Requires \n or + | Natural newlines |
| Quotes | Must escape \" | No escaping needed |
| Indentation | Manual | Auto-stripped |
| Runtime type | String | String (identical) |
| Performance | Same | Same (compile-time sugar) |

What are common mistakes?

JAVA
// WRONG: content on the same line as opening """
String wrong = """content""";  // COMPILE ERROR: no line terminator after """

// WRONG: forgetting that closing """ position controls indentation
String query = """
SELECT * FROM accounts
WHERE branch = 'HDFC'
""";  // closing at column 0: no stripping, full indentation preserved

// CORRECT: align closing """ with content indentation
String query = """
        SELECT * FROM accounts
        WHERE branch = 'HDFC'
        """;  // closing at same indent: incidental whitespace stripped

What should a senior engineer know?

  • Text blocks produce ordinary String objects. They can be compared with == (if interned) or .equals() like any string.
  • .formatted() (instance method) is the text block equivalent of String.format(). It is more readable when chained.
  • .stripIndent() and .translateEscapes() are the methods the compiler uses internally; you rarely call them directly.
  • Text blocks work well with Pattern.compile() for embedding regex patterns without double-escaping backslashes.

What are common interview follow-up questions?

  • Are text blocks a new type? (No. They produce java.lang.String at compile time.)
  • Can text blocks contain triple quotes? (Yes, escape one of the quotes: \""" or ""\".)
  • Do text blocks support interpolation natively? (Not yet. String templates were previewed and withdrawn. Use .formatted() for now.)

Visual Overview

DIAGRAM
  Text Block Processing:

  Source Code:
  ┌─────────────────────────────────────┐
  │  String json = """                  │
  │          {"from": "SAV2001"}        │
  │          """;                       │
  └──────────────┬──────────────────────┘
                 │
                 ▼
  Compiler Steps:
  1. Remove opening line (after """)
  2. Find minimum indentation (closing """ position)
  3. Strip that many leading spaces from each line
  4. Process escape sequences (\s, \, \n)
  5. Produce ordinary String constant
                 │
                 ▼
  Runtime String:
  ┌─────────────────────────────────────┐
  │  {"from": "SAV2001"}\n             │
  └─────────────────────────────────────┘

Key Takeaway

Text blocks eliminate escape characters and concatenation for multi-line strings. Write JSON, SQL, HTML, and XML exactly as they appear. Quotes do not need escaping, newlines are preserved, and common leading whitespace is stripped by the compiler based on the closing delimiter position.

The .formatted() method provides variable interpolation: """\n{"from": "%s"}\n""".formatted(accountId) produces clean JSON with injected values. The trailing backslash suppresses newlines for line joining, and \s preserves trailing spaces.

Text blocks are compile-time sugar. They produce ordinary String objects with no runtime cost. They interoperate with all String methods: .trim(), .strip(), .contains(), regex matching, and everything else. In a banking application, embedded SQL queries and JSON payloads become readable and maintainable instead of cluttered with escape characters.

Remember one sentence: text blocks use triple quotes to write multi-line strings without escaping, and the closing delimiter position controls indentation stripping.

---

Share
Use ← → arrow keys to navigate