Java Text Blocks: Simplifying Multiline Strings in Java 15

Explore Java Text Blocks, introduced as a standard feature in Java 15, which simplify the handling of multiline strings, including JSON, XML, and HTML. Learn how text blocks, initially previewed in Java 13, improve code readability and reduce the need for escape characters.



Java - Text Blocks

Introduction to Text Blocks

Java 15 introduced text blocks as a standard feature to simplify handling of multiline strings, such as those found in JSON, XML, and HTML. Initially, text blocks were previewed in Java 13.

Text blocks allow for easy writing of multiline strings without the need for line breaks, represented by \r\n. These text blocks share the same methods as the String class, including contains(), indexOf(), and length().

The main purpose of text blocks is to declare multi-line strings efficiently. Previously, developers used string concatenation, the StringBuilder append method, or the String join method to create multiline strings, which resulted in messy code due to required line terminators and delimiters. Text blocks offer a cleaner alternative by utilizing triple double quotes """.

Text Block Syntax

A text block is an enhancement to the existing String object, utilizing a special syntax that begins with """, followed by a newline, and ends with """. Any content between these triple quotes will be preserved as-is.

Syntax

String textBlockJSON = """
{
    "name" : "Alex",
    "RollNO" : "42"
}
""";

The equivalent string can be written using the older syntax as follows:

Equivalent Syntax

String stringJSON = "{\r\n" 
        + "   \"Name\" : \"Alex\",\r\n" 
        + "   \"RollNO\" : \"42\"\r\n" 
        + "}";  

Example of Java Text Block

In this example, we print a JSON string using both a text block and the string concatenation method.

Code Example

package com.tutorialsarena;

public class Tester {

public static void main(String[] args) {
    String stringJSON = "{\r\n" 
    + "   \"Name\" : \"Alex\",\r\n" 
    + "   \"RollNO\" : \"42\"\r\n" 
    + "}";  

    System.out.println(stringJSON);

    String textBlockJSON = """
    {
        "name" : "Alex",
        "RollNO" : "42"
    }
    """;
    System.out.println(textBlockJSON);
}   
}

Output

Output

{
"Name" : "Alex",
"RollNO" : "42"
}
{
"name" : "Alex",
"RollNO" : "42"
}

Text Block String Operations

Text blocks behave like regular strings and can be compared using the equals() method or the equality operator ==.

Comparison Example

// compare the content, 
textBlockJSON.equals(stringJSON);

// compare the objects
textBlockJSON == stringJSON;

Text blocks support all string operations, such as indexOf() and contains().

String Operations Example

// check if text block contains a provided string
textBlockJSON.contains("Alex");

// get the length of string content
textBlockJSON.length();

Example: Text Block String Operations in Java

This example demonstrates various string operations while comparing a text block with an equivalent string.

Code Example

package com.tutorialsarena;

public class Tester {

public static void main(String[] args) {
    String stringJSON = "Alex";

    String textBlockJSON = """
    Alex""";
    // compare the content
    System.out.println(textBlockJSON.equals(stringJSON));

    // compare the objects
    System.out.println(textBlockJSON == stringJSON);

    // text block supports all string operations
    System.out.println("Contains: " + textBlockJSON.contains("Alex"));
    System.out.println("indexOf: " + textBlockJSON.indexOf("Alex"));
    System.out.println("Length: " + textBlockJSON.length());
}   
}

Output

Output

true
true
Contains: true
indexOf: 0
Length: 4

Text Block Methods

  • stripIndent() - Removes incidental white spaces from the start and end of the string.
  • translateEscapes() - Translates the escape sequences according to string syntax.
  • formatted() - Similar to the String format() method, it supports formatting within text block strings.

Example of Formatting with Text Blocks

Consider the following example that demonstrates the use of the formatted() method:

Code Example

public class APITester {

public static void main(String[] args) {
    String textBlockJSON = """
        {
        "name" : "%s",
        "RollNO" : "%s"
        }
        """.formatted("Alex", "42");
    System.out.println(textBlockJSON);
}   
}

Output

Output

{
"name" : "Alex",
"RollNO" : "42"
}