Java Text Blocks Example
In this article, we will discuss the Java Text Blocks. Text Blocks are available in multiple distributions of Java (Oracle, OpenJDK, etc) but we will cover mostly the one present in Oracle JDK.
With text blocks, introduced in Oracle Java 13, it became easier for you to work with multiline string literals, without the need to escape the special characters in string literals or use concatenation operators for values that span multiple lines.
1. What are Java Text Blocks?
The String data type is perhaps one of the most used types by Java developers. It can store anything from a few characters to multiple lines in any language. But this flexibility results in making some string values difficult to read or modify; for example, those with embedded quotation marks, escape characters, or strings that span more than one line.
Let’s see how text blocks, a new preview feature in Java 13, can help.
You can use text blocks to define multiline String literals with ease. You can also control how the values are formatted. For example, let’s look at the following HTML snippet:
String html = """
<HTML>
<BODY>
<H1>"Hi, I am a Text Block!"</H1>
</BODY>
</HTML>""";
Notice the three quotation marks that delimit the beginning and end of the block. Consider what the previous alternative in Java would have been:
String html = "<HTML>" +
"\n\t" + "<BODY>" +
"\n\t\t" + "<H1>\"Hi, I am a Text Block!\"</H1>" +
"\n\t" + "</BODY>" +
"\n" + "</HTML>";
The Text Block version has considerably high readability than the one with all the escape characters.
2. Syntax of Text Blocks
A text block is defined using three double quotes ("""
) as the opening and closing delimiters. The opening delimiter can be followed by zero or more white spaces and a line terminator. A text block value begins after this line terminator. There are no similar rules for the closing delimiter.
A consequence of this is that the following examples are invalid text blocks because they don’t include a line terminator (multilineValue1 does have a white space but no line terminator and multilineValue2 neither have white space nor the line terminator) after the opening delimiter:
String multilineValue1 = """ """;
String multilineValue2 = """""";
Text blocks were released in Java 13 as a preview language feature, but preview language features are not incomplete
To use preview language features, you need to specifically enable them using compilation and runtime. This ensures that you don’t use preview features unwittingly.
To compile a source file with text blocks, use the options --enable-preview
and -release 13
. For instance, to compile a file called Main.java
, you need to use the following command.
javac --enable-preview --release 13 Main.java
Since these are preview features and subject to change, you’ll get compiler warnings when you execute the preceding command.
To execute class Main
, you must use the option --enable-preview
:
java --enable-preview Main
Traditional String values and text blocks are both compiled to the same type: String. The bytecode class file between traditional String or a text block. This implies that text block values are stored in the string pool.
Developers often work with multiline string values such as JSON, HTML, XML, or regular expression (regex) data. Here’s how working with a multiline JSON value would become simpler with text blocks:
String jcgJson = """
{
"name": "Java Code Geeks",
"version": "1.0.0",
"dependencies": "Java Code Geeks"
}
""";
Without any visual clutter due to escape sequences and concatenation operators, the JSON value can be edited with ease.
Just in case you think that’s not beneficial, here’s how you might have defined your JSON values with traditional Strings:
String jcgJson =
"{" +
"\"name\": \"Java Code Geeks\"," +
"\"version\": \"1.0.0\"," +
"\"dependencies\": \"Java Code Geeks\" +
"}";
You can store a multiline SQL query using a TextBlocks
variable easily as shown below.
String query = """
SELECT name, age
FROM EMP
WHERE name = 'John'
AND age > 20
""";
You can add various escape sequences to text blocks just as you would add them to your String literals. For instance, you can include newlines in your text blocks by placing the values on multiple lines or by using escape sequences such as \n
. In the following code, I'm
and happy
will be on separate lines:
String html = """
<HTML>
<BODY>
<H1>I'm \nhappy</H1>
</BODY>
</HTML>""";
Text blocks can be concatenated with traditional String values and vice versa. Here’s an example:
String concatenate(Object obj) {
return """
I am Inevitable
"""
+ obj +
"I am IronMan";
}
you can use format()
or any of the other methods of String on a TextBlock.
Raw string literals interpret all the characters including indentation. So whitespace which was supposed just to make your source code easier to read actually becomes part of your strings. In the vast majority of cases, this is not the desired behavior.
Fortunately, Java compiler removes unwanted whitespace when compiling Text Blocks.
- All the trailing whitespace is removed from the end of the lines.
- Leading common whitespace is removed from the start of each line.
Let’s look at the following code:
Main.java
public class Main {
public static void main(String[] args) {
String html = """
<html>
<body>
<p>Text Blocks are awesome!</p>
</body>
</html>
""";
}
}
The HTML code snippet contains a whole lot of whitespace, but it does not really belong to it. It just makes it well-aligned within the source file.
In other words: If every line in the snipped starts with 22 whitespaces, we can ignore them. These 22 spaces are common whitespace prefix, which can be ignored and only what is on top of that should be kept.
Let’s replace common prefix with .
. All of these spaces will be discarded. Only spaces marked with -
will be kept as they exceed the common whitespace prefix.
String html = """
......................<html>
......................--<body>
......................----<p>Text Blocks are awesome!</p>
......................--</body>
......................</html>
......................""";
The result will be:
<html>
<body>
<p>Text Blocks are awesome!</p>
</body>
</html>
Note that in this step only direct whitespace is removed.
As part of the Text Blocks proposal, there are three new Methods of String class.
translateEscapes()
– translates escape sequences in the string except for Unicode ones.stripIndent()
– strips away common whitespace from the beginning of each line.formatted(Object... args)
– Convenience method, the equivalent of String.format(string, args)
3. Summary
To summarize, we have reviewed the Java Text Blocks feature introduced in Java 13. Text blocks help developers work with multiline string values with ease. Remember that text blocks are a preview feature at this point and subject to change. More details about that can be read here.
4. Download the source code
You can download the full source code of this example here: Java Text Blocks Example