Text Blocks is a preview feature in Java 14, and in Java 15 became a standard feature. It is a multi-line string literal that makes long strings easier to use and read.
Text Blocks start with “”” (triple-double quotes) and a new line and end with “”” (triple-double quotes). Similar to what we have in the Python programming language.
Syntax of the Text Blocks
String multilineText= """ Hi, this is one simple example of a multiline text""";
We don’t need to escape double-quotes and new lines inside a Text Block.
JSON string before Java 14:
class Test { public static void main(String[] args) { String example = "{\"key1\":\"value1\",\"key2\":" + "\"value2\",\"key3\":\"value3\"}"; System.out.println(example); } }
class Test { public static void main(String[] args) { String example = """ { "key1": "value1", "key", "value2" } """; System.out.println(example); } }
Java 14 New Escape Sequences
In Java 14, there are 2 additional additions to the Text Blocks:
- \ – to prevent implicit new line character
- \s – to prevent removal of the spaces
1. Escape line-terminator
In some situations, we want our long string to stay in line, but we write it as a Text block for clarity. To prevent inserting an implicit newline character by the JVM, we can add \.
Example:
class Test { public static void main(String[] args) { String example = """ {\ "key1": "value1",\ "key2", "value2",\ "key3", "value3"\ }\ """; System.out.println(example); } }
2. Escaping Spaces
In a Text Block, all spaces will be removed/stripped by default.
Example:
String example = """ username: "john", "password" "john123" """;
If we want to add some spaces in the first line, just after the “john”, the same will be removed by default.
We can prevent that by adding \s at the end of the line:
String example = """ "username: "john", \s "password" "john123" """;
and the output is:
Output: "username: "john",.......... "password" "john123"
I’ve added ‘.‘ (dots) in the output to help you understand better where the spaces are.
That’s it!