Java Text Blocks


Text Blocks in Java provide a more readable and convenient way to write multi-line strings. They were introduced to simplify the creation of strings that span multiple lines, which is particularly useful for writing JSON, XML, SQL, or HTML content.

P.S. Minimum Java 15 is required.

Syntax

A text block is defined using triple double-quotes ("""), and it can span multiple lines. The content inside the text block is preserved as-is, including newlines and indentation.

Example: Here is an example of using a text block to define a JSON string:

String json = """
    {
        "name": "Manish",
        "age": 30,
        "city": "New York"
    }
    """;
System.out.println(json);

Use Cases

  1. JSON/XML/HTML Content: Text blocks are ideal for embedding JSON, XML, or HTML content directly in your code without the need for escaping quotes or newlines.
  2. SQL Queries: Writing complex SQL queries becomes more readable and maintainable.
  3. Multi-line Strings: Any scenario where you need to handle multi-line strings, such as generating formatted text or documentation.

Example Use Case: SQL Query

Here is an example of using a text block to define a multi-line SQL query:

String sqlQuery = """
    SELECT id, name, age
    FROM users
    WHERE age > 18
    ORDER BY name;
    """;
System.out.println(sqlQuery);

Conclusion

Text blocks improve the readability and maintainability of your code by allowing you to write multi-line strings in a more natural and less error-prone way.

References

  1. JEP 378: Text Blocks
  2. Sealed Interface in Java 17

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.