Codectionary / Developer documentation / Java

Multiline Strings with Text Blocks

Write readable multiline text while understanding indentation and the final newline.

What it is and why to use it

Text blocks make embedded HTML, templates and other multiline text easier to read than a chain of quoted strings and newline escapes. They produce ordinary String values. Text blocks are a standard feature from Java 15 and are available under the Java 17 baseline used here.

How it works

An opening triple quote is followed by a line terminator. Java normalises line endings and removes incidental indentation according to the text block rules. In this example the closing delimiter is on its own line, so the value includes a newline after Welcome. strip removes leading and trailing whitespace for the second print.

Common mistakes and limitations

A text block does not interpolate variables or automatically escape HTML or SQL. Its spaces and final newline still matter. Parameterised SQL and context-appropriate output escaping remain necessary in real applications.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

String text = """
    Hello
    """;

Examples

Multiline Strings with Text Blocks

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  public static void main(String[] args) {
    String message = """
        Hello, John
        Welcome
        """;
    System.out.print(message);
    System.out.println(message.strip().endsWith("Welcome"));
  }
}
  1. The indentation shared by the content and closing delimiter is removed from the resulting string.
  2. print writes the two lines; the text block itself supplies the newline after Welcome.
  3. strip returns another String without edge whitespace, so endsWith("Welcome") is true. Use this technique for readable messages or templates whose whitespace you understand.
  4. Expected output: Hello, John Welcome true

Best practices

  • Inspect whitespace when output is used in a protocol or snapshot.
  • Keep dynamic data separate from executable query text.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading