Java Text Blocks

Java Programming Tutorials


Java text blocks let you write multiline string literals with three double-quote characters. They reduce escaped quotes and explicit newline sequences in HTML, JSON, SQL, templates, and other structured text.

Text blocks became a permanent Java language feature in Java 15. They still create ordinary String objects, so you can compare, format, concatenate, and pass them to existing APIs in the same way as quoted string literals.

Text Block Syntax

A text block starts with three double quotes followed by a line terminator. Its content begins on the next line and ends at the closing delimiter.

Syntax:

// The opening delimiter must be followed by a line break.
String message = """
        First line
        Second line
        """;

The line after the opening delimiter is not an automatic blank line. The closing delimiter controls indentation and whether the resulting string ends with a newline.

Create a Multiline Receipt

The following example keeps a receipt template readable and inserts values with String.formatted().

Example:

public class Main {
    public static void main(String[] args) {
        String customer = "Asha";
        int orderId = 2048;

        // A text block keeps the multiline receipt readable.
        String receipt = """
                Customer: %s
                Order ID: %d
                Status: Ready
                """.formatted(customer, orderId);

        System.out.print(receipt);
    }
}

Output:

Customer: Asha
Order ID: 2048
Status: Ready

Understand Incidental Indentation

Java removes incidental indentation so your text can line up with surrounding source code without adding unwanted spaces to the result. The compiler finds the common leading whitespace of the nonblank lines and the closing delimiter, then removes that amount.

Example:

// Intentional indentation inside the list remains in the String.
String menu = """
        Drinks
          Tea
          Coffee
        """;

System.out.print(menu);

Output:

Drinks
  Tea
  Coffee

If you move the closing delimiter farther left, it can reduce how much indentation Java removes. Keep it aligned with the content margin when you want the usual source-code layout.

Control the Final Newline

A closing delimiter on its own line normally leaves a newline after the last content line. Place the delimiter immediately after the last character to omit that final newline.

Example:

// This text block does not end with a newline.
String status = """
        Payment approved""";

System.out.println(status.length());

Output:

16

Use Quotes Without Repeated Escapes

You can include one or two double quotes directly. Escape a quote only when a sequence could form the closing three-quote delimiter.

Example:

// JSON keys and values remain easy to read.
String profileJson = """
        {
          "name": "Noah",
          "role": "editor"
        }
        """;

Text blocks are not raw strings. Java still processes escape sequences such as newline, tab, backslash, and Unicode escapes.

Preserve Spaces with \s

The compiler removes trailing whitespace from each line. Use the \s escape when a trailing space belongs to the data. The escape represents one space and prevents that position from disappearing.

Example:

// Preserve one space after each label before concatenated values.
String labels = """
        Name:\s
        City:\s
        """;

System.out.print(labels);

Join Source Lines with a Line Continuation

A backslash at the end of a text-block line suppresses the following newline. This lets you wrap a long string in source code without changing the produced text.

Example:

// Wrap the source while producing one output line.
String sentence = """
        Your order is ready for collection \
        from the central counter.
        """;

System.out.print(sentence);

Output:

Your order is ready for collection from the central counter.

Format HTML and SQL Clearly

Text blocks improve readability when the text naturally spans several lines. Keep external values separate from the literal, and use the safe parameter mechanism supplied by your database or template library.

Example:

String userName = "Emily";

// Format trusted display text into a small HTML fragment.
String html = """
        <section class="profile">
          <h2>%s</h2>
          <p>Account active</p>
        </section>
        """.formatted(userName);

Note: A text block does not make SQL or HTML input safe. Continue to use prepared statements, output escaping, and the security rules required by the destination.

Useful String Methods

Method Purpose
formatted() Replaces format specifiers with supplied values
stripIndent() Removes incidental indentation from an existing string
translateEscapes() Processes escape sequences in a string at runtime

Conclusion

Java text blocks make multiline strings easier to read without introducing a new string type. The compiler normalizes line endings, removes incidental indentation, and supports escapes for spaces and line continuation. Use text blocks for naturally multiline content, control the closing delimiter carefully, and keep normal security practices when inserting external values.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram