Part 32: Java 13 – Text Blocks – Writing Multi-Line Strings the Way They Were Meant to Be

Introduction

Strings are everywhere in enterprise applications.

Every day, developers write:

  • SQL queries
  • JSON payloads
  • XML requests
  • SOAP messages
  • HTML emails
  • Markdown
  • YAML
  • GraphQL queries
  • Kafka event payloads
  • REST request bodies

Unfortunately, before Java 13, writing multi-line strings was one of Java’s biggest frustrations.

Consider a simple JSON document.

{
  "customerId":1001,
  "name":"Rahul",
  "country":"India"
}

Writing this in Java required escaping quotes and concatenating every line.

The result was difficult to read, difficult to maintain, and very easy to break.

Java 13 introduced Text Blocks (preview in Java 13, finalized in Java 15), allowing developers to write multi-line strings almost exactly as they appear in the final output.

For enterprise developers, this dramatically improves readability when working with SQL, JSON, XML, HTML, configuration files, and integration testing.


Learning Objectives

By the end of this article, you will be able to:

  • Understand why Text Blocks were introduced.
  • Write readable multi-line strings.
  • Replace string concatenation.
  • Generate JSON and XML payloads.
  • Write embedded SQL queries.
  • Create HTML email templates.
  • Use Text Blocks in Spring Boot applications.
  • Apply enterprise best practices.

Before Java 13

Suppose we want to create a JSON payload.

String json = "{\n" +
        "  \"customerId\":1001,\n" +
        "  \"name\":\"Rahul\",\n" +
        "  \"country\":\"India\"\n" +
        "}";

Problems:

  • Escape characters everywhere.
  • Difficult to edit.
  • Hard to compare with actual JSON.
  • Easy to introduce syntax errors.

Java 13 Solution

String json = """
{
  "customerId":1001,
  "name":"Rahul",
  "country":"India"
}
""";

No escaping.

No concatenation.

The Java code closely matches the actual JSON.


What Is a Text Block?

A Text Block is a multi-line string literal enclosed within triple double quotes.

Syntax:

String text = """
Hello Java
Hello Spring
Hello Microservices
""";

The compiler creates a normal String.

Nothing changes at runtime.


SQL Queries

One of the biggest advantages of Text Blocks is writing SQL.

Before Java 13

String sql =
        "SELECT c.customer_id, " +
        "c.name, " +
        "o.order_total " +
        "FROM customers c " +
        "JOIN orders o " +
        "ON c.customer_id = o.customer_id " +
        "WHERE c.status='ACTIVE'";

Reading this query is difficult.


Java 13

String sql = """
SELECT c.customer_id,
       c.name,
       o.order_total
FROM customers c
JOIN orders o
  ON c.customer_id = o.customer_id
WHERE c.status = 'ACTIVE'
""";

The SQL is now readable exactly as a database developer expects.


JSON Payloads

REST request body:

String request = """
{
  "orderId":1001,
  "amount":5000,
  "currency":"INR",
  "paymentMethod":"UPI"
}
""";

Much easier to maintain than escaped strings.


XML Documents

String xml = """
<Customer>
    <Id>1001</Id>
    <Name>Rahul</Name>
    <Country>India</Country>
</Customer>
""";

Ideal for SOAP integrations and legacy enterprise systems.


HTML Templates

Suppose a notification service sends emails.

String html = """
<html>
    <body>
        <h1>Welcome</h1>
        <p>Your account has been created successfully.</p>
    </body>
</html>
""";

No concatenation required.


GraphQL Queries

Modern applications frequently communicate using GraphQL.

String query = """
query Customer {
    customer(id:1001){
        id
        name
        email
    }
}
""";

The query remains readable and easy to modify.


Kafka Event Payload

String event = """
{
  "event":"ORDER_CREATED",
  "orderId":1001,
  "status":"SUCCESS"
}
""";

Useful in testing or integration scenarios.


YAML Configuration

String yaml = """
database:
  url: jdbc:oracle:thin:@localhost
  username: admin
  password: secret
""";

Although configuration files are typically external, Text Blocks are useful in tests and examples.


Dynamic Values

Text Blocks are ordinary strings.

You can still use formatting.

Example:

String json = """
{
  "customerId": %d,
  "name": "%s"
}
""".formatted(1001, "Rahul");

This is cleaner than repeated string concatenation.


Spring Boot REST Client

Suppose a microservice calls another service.

String requestBody = """
{
    "customerId":1001,
    "product":"Laptop",
    "quantity":2
}
""";

The body can be passed directly to an HTTP client or serialized into a request object where appropriate.


Integration Testing

Text Blocks are especially valuable in tests.

Example:

String expected = """
{
  "status":"SUCCESS",
  "code":200
}
""";

Comparing expected and actual payloads becomes much easier.


Whitespace Handling

Java removes incidental indentation from Text Blocks.

Example:

String text = """
        Java
        Spring
        Docker
        """;

Produces:

Java
Spring
Docker

This allows Text Blocks to remain aligned with surrounding code while producing clean output.


Escape Sequences

Most escaping disappears.

Before:

"\"Java\""

After:

"""
"Java"
"""

Only special cases still require escape sequences.


Enterprise Use Cases

Text Blocks are ideal for:

  • SQL queries
  • Native JPA queries
  • JSON payloads
  • XML messages
  • HTML templates
  • GraphQL
  • Email content
  • Kafka event samples
  • Mock server responses
  • Integration tests

Performance

Text Blocks are compiled into ordinary String objects.

There is no runtime performance advantage.

Their benefit is readability and maintainability.


Common Mistakes

Building JSON Manually in Production

Although Text Blocks improve readability, manually constructing JSON for production APIs is still error-prone.

Prefer serialization libraries such as Jackson when generating request and response payloads from Java objects.


Embedding Very Large Documents

Very large HTML or SQL templates are often better stored in external resource files.


Confusing Text Blocks with Templates

Text Blocks are string literals.

They are not template engines.

Dynamic values must still be inserted explicitly (for example, using formatted() or other techniques).


Best Practices

✔ Use Text Blocks for SQL, JSON, XML, and HTML.

✔ Prefer Text Blocks over string concatenation for multi-line content.

✔ Use formatted() for simple value substitution.

✔ Continue using serialization libraries for production JSON.

✔ Keep very large templates in external files when appropriate.


Interview Questions

Why were Text Blocks introduced?

To simplify the creation of multi-line strings and improve readability by eliminating excessive escaping and concatenation.


Do Text Blocks create a new String type?

No.

They compile into ordinary String objects.


Can Text Blocks contain quotes?

Yes.

Most double quotes do not require escaping.


Should production JSON be created manually using Text Blocks?

Generally no.

Text Blocks are excellent for examples, tests, and static content, while production applications should usually rely on object serialization libraries such as Jackson.


Do Text Blocks improve runtime performance?

No.

Their primary benefit is improved readability and maintainability.


Summary

Text Blocks modernize one of Java’s most frequently used language features by making multi-line strings readable, maintainable, and far less error-prone. They are particularly valuable in enterprise applications where SQL, JSON, XML, HTML, and integration payloads are common.

Although they do not change runtime behavior, they significantly improve developer productivity and reduce the boilerplate associated with traditional string concatenation.


Coming Up Next

Part 33 – Java 14: Records – Eliminating Boilerplate for Immutable Data Models

We’ll explore one of the biggest language improvements since Lambdas:

  • Why Records were introduced
  • Records vs POJOs
  • Constructors
  • Validation
  • Immutability
  • equals(), hashCode(), and toString()
  • Records with Jackson
  • Records in Spring Boot
  • Records as DTOs
  • Records vs JPA Entities
  • Enterprise best practices

This will be one of the most important articles in the series because Records fundamentally change how we model data in modern Java applications.

Leave a Reply

Your email address will not be published. Required fields are marked *