Text blocks in Java 14

Java 14 introduces a new feature called Text Blocks which aims to simplify the creation and formatting of multiline strings. Text Blocks provide a more readable and concise way to define multiline strings compared to traditional string concatenation or escape characters. In this blog post, we will explore how to use Text Blocks in Java 14.

Enable Preview Feature

Before we dive into Text Blocks, it’s important to note that Text Blocks are available as a preview feature in Java 14. To enable this feature, simply add the --enable-preview flag to the Java compiler and runtime.

Syntax and Usage

The syntax for Text Blocks in Java 14 is as follows:

String textBlock = """
    This is a 
    multiline
    text block.
    """;

To define a Text Block, we use triple double quotes (""") instead of double quotes (""). The text block content is then placed between the triple quotes. Unlike regular strings, Text Blocks preserve both the indentation and line breaks, making it easier to format and read multiline strings.

Handling Whitespaces

Text Blocks provide flexibility in handling whitespaces using the escape sequences `

, \t, and \`. These escape sequences allow us to include line breaks, tab characters, and backslashes within a Text Block. Here’s an example:

String textBlock = """
    This is a \n\tmultiline\n\t\ntext block with \\backslash.
    """;

In the above example, the escape sequences are evaluated and rendered correctly when the Text Block is printed.

Stripping Whitespaces

By default, Text Blocks preserve whitespaces, including leading and trailing whitespaces on each line. However, Java 14 provides the ability to control the stripping of these whitespaces by using the strip and stripIndent methods.

The strip method removes leading/trailing whitespaces from the entire Text Block:

String textBlock = """
    This is a 
    multiline
    text block.
    """;

String strippedBlock = textBlock.strip();

The stripIndent method removes the common leading indentation from all lines:

String textBlock = """
    This is a 
        multiline
            text block.
    """;

String strippedBlock = textBlock.stripIndent();

Both methods return a new string with the respective whitespaces stripped. Note that the original Text Block remains unchanged.

Conclusion

Text Blocks in Java 14 provide a more intuitive way to define and work with multiline strings. Their syntax and flexibility make formatting and reading multiline strings much easier, enhancing code readability. However, as it is a preview feature, it is recommended to use Text Blocks with caution in production environments.

To learn more about Text Blocks and other features in Java 14, please refer to the official Java documentation.

#references: