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
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:
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:
+
operator to concatenate multiple string literals. This is error-prone and difficult to read.
Pros
Cons
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 likeString.format()
or string concatenation to include variables within a text block.