It’s now possible to create multi-line String literal without the need to concatenate strings on line breaks. This makes text blocks a useful feature for writing long strings that require formatting or readability.
Introduction:
A text block in Java is a new language feature introduced in Java 15 that allows developers to write multi-line strings with improved readability and maintainability.
Syntax:
Text blocks are enclosed between three double quotes (“””) and can contain any number of lines, with leading and trailing whitespaces being removed automatically.
The indentation level of the closing quotes determines the minimum indentation level of the block.
Examples:
Plain Text String Example:
1 2 3 4 5 |
String textBlock = """ This is a multi-line text block that spans across several lines with no need for escape sequences. """; |
HTML Code String Example:
1 2 3 4 5 6 7 |
String htmlBlock = """ <html> <body> <p>Hello, world</p> </body> </html> """; |
SQL Query String Example:
1 2 3 4 5 |
String queryBlock = """ SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB" WHERE "CITY" = 'INDIANAPOLIS' ORDER BY "EMP_ID", "LAST_NAME"; """; |
Additional Methods:
Following are the additional methods added to the String class to support text blocks:
String::stripIndent()
: used to strip away incidental white space from the text block contentString::translateEscapes()
: used to translate escape sequencesString::formatted(Object... args)
: simplify value substitution in the text block