Easy java java-21

What are text blocks?

The 30 second answer

Text blocks, final in Java 15, are multi-line string literals between three double quotes. You write JSON, SQL or HTML as it looks, without escaping every quote or joining lines with plus signs. The compiler removes the common indentation, so you can indent the block with your code. The result is a normal String, so you can call formatted on it to fill in values.

String json = """
    {
      "id": %d,
      "name": "%s"
    }
    """.formatted(id, name);

Rules:

  • The opening """ must be followed by a line break.
  • Incidental indentation (the common leading whitespace) is removed; the position of the closing """ affects it.
  • Trailing spaces are stripped. Use \s to keep a space, and \ at the end of a line to join lines without a newline.
  • Line endings are normalized to \n.

Text blocks were previewed in Java 13 and 14 and became final in Java 15.

Sources: JEP 378: Text Blocks, Programmer's Guide to Text Blocks

Sources (0)
See inline citations in the answer above.