Text Blocks – Simplifying Multi-Line Strings in Java
JEP 368 introduces text blocks as a preview feature in Java 14, offering a new way to write multi-line string literals. This feature aims to improve readability and maintainability compared to traditional string concatenation, especially for scenarios involving extensive string content.
Here’s a breakdown of key aspects:
Motivation:
- Concatenating strings for multi-line content can be cumbersome and error-prone, requiring escape sequences and proper indentation.
- JEP 368 addresses this by providing a new syntax for writing multi-line strings with minimal escaping and automatic indentation preservation.
Syntax:
- Text blocks are enclosed by triple double quotes (“`).
- Whitespace and indentation within the opening and closing delimiters are preserved as part of the string content.
- No escape sequences are needed for newlines or other special characters within the block, except for double quotes (“”), which require escaping with a backslash (“).
String oldString = "This is a string\n" +
"written with concatenation\n" +
"and requires escaping newlines \\n.";
String textBlock = """
This is a string
written with a text block
and preserves indentation and newlines.
No need to escape "quotes".
""";
System.out.println(oldString);
System.out.println(textBlock);
Output : This is a string written with concatenation and requires escaping newlines \n. This is a string written with a text block and preserves indentation and newlines. No need to escape “quotes”.