Text blocks are multiline strings that can be defined with a variable.
Normally, You can define the variable initialized with a string literal in one line using double quotes.
String message="Welcome to my site"
If you want to assign a multi-line string to a string variable, You have to use escape characters and double quotes
Java 13 and 14 released the Text Block for a String as a Preview feature. Java 15 released Text blocks as a usable feature.
Text blocks can be used in multiple places. Text block always starts with three double quotes
This is the new syntax for writing multi-line strings without escape characters.
- You can define string literal with multiple lines as given below
Here is an example
String multiLineStr = """
line 1
line 2
line 3
""";
- Another way, used as an argument
For example, the println
method accepts a string of text blocks.
System.out.println(""" line 1 line 2 line 3 “”");
String text block methods
New methods are added to the String class
- formatted method
String formatted(Object... args)
Here is an example
String result = """
Id: %s
Name: %s
Marks: $%.2f
""".formatted(id, name, marks);
- String stripIndent()
stripIndent() method removes spaces from a multi-line string.
- String translateEscapes() translateEscapes method translates escape characters.
What is a text block in Java?
Text block is a way of storing multi-line strings simply and easily in java15. It is not required to have line breaks or escape characters for multi-line. Define multi-line string, enclosed in triple quotes.