Java 17 introduced text blocks to simplify the use of multiline strings, making it much easier to include and manage multiline text in your Java applications. Text blocks were actually introduced in Java 15 but were further refined and are fully supported in Java 17.
What Are Text Blocks?
A text block is a multiline string literal declared with triple double-quotes ("""
). It preserves the format of the text, including newlines and whitespace, making it ideal for creating strings like XML, JSON, HTML, SQL queries, or large blocks of text.
Syntax and Usage
Here’s the basic syntax:
String multilineString = """
Line 1
Line 2
Line 3
""";
Key Features of Text Blocks:
- Multiline Strings: Text blocks support strings spanning multiple lines.
- Automatic Line Breaks: No need to write
\n
at the end of each line. - Automatic Handling of Whitespace: Leading whitespace can be trimmed automatically.
- Readable for Formats: Excellent for embedding JSON, SQL, XML, or other text-based formats.
Example Usages
1. JSON or XML Example
String json = """
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
""";
System.out.println(json);
2. SQL Query Example
String sql = """
SELECT *
FROM users
WHERE age > 18
AND city = 'New York';
""";
System.out.println(sql);
3. Embedding an HTML Template
String html = """
<html>
<body>
<h1>Hello, World!</h1>
<p>This is an example of a text block.</p>
</body>
</html>
""";
System.out.println(html);
Notes on Formatting and Indentation
- Indentation Control: Java automatically determines the minimum level of indentation for the text block and removes it by default.
For example:
String indentedText = """ This text block is indented uniformly. """;
Outputs:
This text block is indented uniformly.
Notice that the leading spaces are omitted while retaining the structure.
-
Custom Alignment: To maintain a consistent indentation in your block while coding, Java aligns the text block based on the whitespace before the ending triple quotes.
Escape Characters in Text Blocks
Text blocks still support escape sequences just like regular strings:
\n
: Newline\t
: Tab\"
: Double quote if needed inside the block\\
: Backslash
Example:
String special = """
She said, \"Hello!\"
This includes some escape sequences: \\n \\t
""";
System.out.println(special);
Summary
Text blocks are a powerful feature, making it easier to embed multiline strings. They reduce the need for concatenation and enhance readability. Whether you’re working with configurations, templates, or queries, they provide a neat and concise way to manage strings in Java applications.
Best Practices
- Use text blocks instead of concatenated strings for multiline text.
- Rely on proper indentation to make the code more readable.
- Test the output when using text blocks with external sources like JSON, SQL, or XML to ensure correctness.
Happy coding! 😊