Java 13 Text Blocks

Java text blocks, introduced in Java 13 as a preview feature and made standard in Java 15, provide a new way to represent multi-line string literals. They simplify the process of writing string literals that span several lines of code, improving readability and reducing the need for most escape sequences.

Summary:

  • Text blocks start and end with triple double quotes (""").
  • They can span multiple lines, allowing you to include newlines and other white spaces directly in the string content.
  • Within a text block, the format of the string is largely preserved as written in the source code, reducing the need for escape sequences.
  • Indentation management: Automatic indentation is based on the position of the closing delimiter, with incidental white space removed.
  • Supports string formatting and expressions with the String.format() method or formatted string literals.

Examples:

  1. Basic Example:

    String textBlock = """
                       Hello,
                       World!
                       """;
    

    This creates a string containing "Hello," followed by a newline, then "World!" and another newline.

  2. Including escape sequences:

    Although less common, you can still use escape sequences in text blocks if needed, such as \" for a double-quote or \\ for a backslash.

    String json = """
                  {
                      "name": "John",
                      "age": 30
                  }
                  """;
    
  3. Comparing to traditional strings:

    Before Java 13, a similar multi-line string would look like this:

    String traditionalString = "Hello,\n" +
                               "World!\n";
    

    The text block version is more readable and easier to maintain.

  4. Indentation and white spaces:

    Text blocks automatically remove incidental white space based on the position of the closing delimiter:

    String message = """
                     Dear Friend,
                       Thank you for your support.
                     Regards,
                     John
                     """;
    

    Here, the string retains the intended indentation levels inside the text block.

  5. Formatting and expressions:

    Text blocks can be used with String.format() or formatted string literals for dynamic content:

    String name = "John";
    int age = 30;
    String userInfo = """
                      Name: %s
                      Age: %d
                      """.formatted(name, age);
    

    This incorporates variable values into the text block.

These examples demonstrate how Java text blocks simplify working with multi-line string literals, making code easier to write and maintain.


Links: Java Big-O summary for Java Collections Framework implementation. Conclusions from CUP theorem for vectors data sets. What is the CAP Theorem?;

All rights reserved by Borg.Net community & Technosphere.