Java tutorials > Modern Java Features > Java 8 and Later > What are text blocks (Java 15)?

What are text blocks (Java 15)?

Text blocks, introduced in Java 15, are multiline string literals that eliminate the need for most escape sequences, format the string in a predictable way, and give the developer control over format when desired. They are designed to improve the readability and maintainability of code containing multiline strings, such as HTML, XML, SQL queries, or JSON payloads.

Basic Syntax

Text blocks are delimited by three double quote characters (""") at the beginning and end. The opening delimiter is followed by a line terminator. The content between the delimiters is treated as a string literal. Leading whitespace is automatically removed, but trailing whitespace is preserved.

String html = """
<html>
  <body>
    <p>Hello, world</p>
  </body>
</html>
""";

System.out.println(html);

Example: SQL Query

This example demonstrates how text blocks can improve the readability of SQL queries embedded in Java code. Without text blocks, you would need to manually escape newlines and quotes, making the code harder to read.

String query = """
SELECT id, name, email
FROM users
WHERE status = 'active'
ORDER BY name;
""";

System.out.println(query);

Example: JSON Payload

Text blocks make it easier to define JSON payloads directly within your Java code without excessive escaping.

String json = """
{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
""";

System.out.println(json);

Concepts Behind the Snippet: Indentation

The compiler determines the indentation by inspecting all the lines of the text block, effectively removing the common whitespace prefix. The position of the closing delimiter, """, determines the 'reference indentation.' All content will be aligned relative to this reference point. You can have inner content indented more than the closing delimiter.

// Example showing indentation behavior
String message = """
    Hello,
      World!
    """;

System.out.println(message.length()); // Output: 17 (includes newline and spaces)
System.out.println(">" + message + "<"); //Shows leading and trailing whitespace


String message2 = """
Hello,
  World!
""";

System.out.println(message2.length()); // Output: 15 (includes newline)
System.out.println(">" + message2 + "<"); //Shows leading and trailing whitespace

Escaping Characters

While text blocks reduce the need for escaping, some characters still require it. For example, to include a literal triple double quote sequence, you need to escape at least one of the quotes with a backslash: \". You also still need to escape backslashes themselves (\\) and the newline character (\n) if you need a literal newline instead of the standard linebreak behavior.

String code = """
String str = \"Hello, world!\";
System.out.println(str);
""";

System.out.println(code);

Real-Life Use Case Section

Text blocks are extremely useful in generating dynamic HTML content for emails, reports, or web pages. They simplify the process of embedding HTML snippets within Java code, enhancing readability and reducing errors.

// Generating an HTML email body
String emailBody = """
<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Hello, User!</h1>
  <p>Thank you for registering. Here's your confirmation link:</p>
  <a href="https://example.com/confirm?token=12345">Confirm Email</a>
</body>
</html>
""";

System.out.println(emailBody);

Best Practices

  • Consistency: Maintain consistent indentation within your text blocks for better readability.
  • Clarity: Use text blocks for multiline strings only. Avoid using them for single-line strings.
  • Placement of Delimiters: Ensure the closing delimiter is at a consistent indentation level relative to the content for easy visual parsing.
  • Escape only when necessary: Avoid excessive escaping, using only when actually necessary.

Interview Tip

During interviews, mentioning that text blocks improve code readability and reduce the need for escaping special characters can demonstrate your understanding of modern Java features and their benefits. Be prepared to discuss the indentation rules and the impact on whitespace.

When to use them

Use text blocks whenever you need to represent multiline strings within your Java code, such as:

  • HTML or XML documents
  • SQL queries
  • JSON payloads
  • Configuration files
  • Any scenario where a long string literal needs to be broken into multiple lines for readability.

Memory footprint

Text blocks, like regular strings, are stored in the String pool. Therefore, the memory footprint is generally similar to that of a traditionally defined multiline string, especially after string interning. The main difference is improved source code readability, which can lead to less debugging and reduced likelihood of errors.

Alternatives

Before Java 15, developers typically used the following alternatives for multiline strings:

  • String concatenation: Using the + operator to concatenate multiple string literals. This is error-prone and difficult to read.
  • StringBuilder/StringBuffer: Appending lines to a StringBuilder/StringBuffer. More efficient than concatenation for many lines, but still verbose.
  • External files: Reading the string from an external file. This separates the string from the code, which is not always desirable.

Pros

  • Improved Readability: Significantly improves the readability of multiline strings.
  • Reduced Escaping: Minimizes the need for escaping special characters like newlines and quotes.
  • Easier Formatting: Provides better control over the formatting of the string.

Cons

  • Learning Curve: Developers need to understand the indentation rules and the behavior of the closing delimiter.
  • Potential for Misinterpretation: Incorrect indentation can lead to unexpected results.
  • Not available in older Java versions: If targeting Java version < 15 it will not be available.

FAQ

  • What is the minimum Java version required to use text blocks?

    Text blocks were introduced in Java 15. You need Java 15 or later to use them.
  • How do I escape a double quote inside a text block?

    You don't need to escape double quotes unless you have three consecutive double quotes. In that case, escape one of them using a backslash: \".
  • How does indentation work in text blocks?

    The compiler determines the indentation by finding the minimum common indentation of all lines in the text block. This common indentation is then removed. The position of the closing delimiter determines the 'reference indentation', used for aligning content.
  • Can I use variables inside a text block?

    Yes, you can use string formatting methods like String.format() or string concatenation to include variables within a text block.