# Modern Java Feature: Text Blocks

Java developers have long struggled with multi-line strings containing escaped characters and awkward formatting. Enter **Text Blocks**, a modern Java feature that makes multi-line string handling *cleaner, more readable, and more expressive*.

## 🆕 What Is a Text Block?

A **text block** is a multi-line string literal introduced as a **preview in Java 13** and **officially added in Java 15**. It allows you to write strings across multiple lines without having to escape every newline or quote.

### Syntax

Text blocks are enclosed in **three double quotes (**`"""`), and must start on a **new line**:

```java
String html = """
    <html>
        <body>
            <h1>Hello, World!</h1>
        </body>
    </html>
    """;
```

This is far more readable than:

```java
String html = "<html>\n" +
              "    <body>\n" +
              "        <h1>Hello, World!</h1>\n" +
              "    </body>\n" +
              "</html>\n";
```

---

### Where Can You Use a Text Block?

Anywhere you can use a regular string, you can use a text block. That includes:

* Assignments to variables
    
* Method arguments
    
* Return values
    
* Annotations
    
* Logs and templates
    

```java
System.out.println("""
    This is a valid
    text block string
    used as an argument.
    """);
```

Text blocks shine when dealing with structured or long-form content:

* 🖥️ **HTML/XML/JSON snippets**
    
* 💾 **SQL queries**
    
* 🤖 **Prompt engineering for AI**
    
* 🧑‍🏫 **Code samples for documentation**
    
* 📜 **Poetry, song lyrics, or long messages**
    

```java
String sql = """
    SELECT id, name
    FROM users
    WHERE active = 1
    ORDER BY name;
    """;
```

---

## Smart Whitespace Handling: Incidental vs Essential

One of the most powerful features of text blocks is their ability to **remove incidental white space**—the indentation that's not part of the string itself but exists to align with your code.

Let’s visualize this with `·` characters to represent leading spaces.

### 👇 Example: Incidental White Space Removed

```java
void writeHTML() {
    String html = """
········<html>
········    <body>
········        <p>Hello World.</p>
········    </body>
········</html>
········""";
    writeOutput(html);
}
```

✅ The output of `html` becomes:

```plaintext
<html>
    <body>
        <p>Hello World.</p>
    </body>
</html>
```

Java determines the *minimum indentation* level (based on the closing delimiter position) and removes it from all lines. This keeps your string readable *and* aligned with your code.

### Preserving Essential White Space

To preserve indentation within the string, just move your content to the right:

```java
void writeHTML() {
    String html = """
········    <html>
········        <body>
········            <p>Hello World.</p>
········        </body>
········    </html>
········""";
    writeOutput(html);
}
```

Result:

```plaintext
    <html>
        <body>
            <p>Hello World.</p>
        </body>
    </html>
```

### Opting Out of Trimming Entirely

If you don’t want Java to trim anything, place the closing delimiter on the far left:

```java
void writeHTML() {
    String html = """
                  <html>
                      <body>
                          <p>Hello World.</p>
                      </body>
                  </html>
""";
    writeOutput(html);
}
```

Java will treat every character as-is, preserving all leading spaces.

> For all the nitty-gritty details, see JEP 355.

---

### Normalize Line Terminators

Text blocks use `\n` (line feed) as the default line terminator on all platforms. If you need to convert them to your system-specific line separator (e.g. `\r\n` on Windows), you can do:

```java
String adjusted = textBlock.replaceAll("\n", System.lineSeparator());
```

This ensures your strings behave consistently across environments.

---

## New String Methods Introduced

Java 15 introduced several useful methods in the `String` class to complement and enhance the text block feature:

| Method | Description |
| --- | --- |
| `stripIndent()` | Removes incidental indentation from a multi-line string |
| `translateEscapes()` | Converts escape sequences like `\\n` or `\\t` into actual characters |
| `formatted(Object...)` | A more readable alternative to `String.format()`, used directly on string instances |

#### Example: 📄 `formatted(...)` with Text Blocks

You can use `.formatted(...)` directly on a text block to inject dynamic values:

```java
String email = """
    Dear %s,

    Your order #%d has been shipped and is expected to arrive by %s.

    Thank you for shopping with us!
    """.formatted("Mirna", 12345, "Friday");

System.out.println(email);
```

**Output:**

```plaintext
Dear Mirna,

Your order #12345 has been shipped and is expected to arrive by Friday.

Thank you for shopping with us!
```

This makes text blocks a great fit for templated emails, prompts, or code generation — with clean syntax and no clutter.

## 📚 Official Documentation

Want to learn more or see additional examples? Check out the official guide:  
👉 [Text Blocks in Java 15](https://docs.oracle.com/en/java/javase/15/text-blocks/index.html)

## Conclusion

Text blocks are a small yet powerful improvement in Java that makes your code easier to read, write, and maintain—especially when working with structured or formatted content.

No more escaping newlines or cramming everything into one line. Just write clean, readable text!

🧭 Stay tuned for more in the *Modern Java Features* series!
