Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to write a multi-line string

Short answer

A text block starts and ends with three quotes """. Line breaks inside it are kept as they are:

void main() {
    String poem = """
            Roses are red,
            Violets are blue.
            """;
    IO.print(poem);
}

Output:

Roses are red,
Violets are blue.

Indentation

Java removes the common indentation of all lines. The position of the closing """ counts too — that lets you keep some indentation in the result:

void main() {
    String json = """
            {
              "name": "Anna"
            }
        """;
    IO.print(json);
}

Output:

    {
      "name": "Anna"
    }

Inserting values

A text block is an ordinary string, so you can call formatted() on it:

void main() {
    String name = "Oleg";
    int total = 42;
 
    String message = """
            Hello, %s!
            Your total is %d €.
            """.formatted(name, total);
    IO.print(message);
}

Output:

Hello, Oleg!
Your total is 42 €.

Without a trailing line break

If the closing quotes are on the same line as the text, there is no final line break. A \ at the end of a line joins it with the next one:

void main() {
    String sql = """
            SELECT name \
            FROM users""";
    IO.println("[" + sql + "]");
}

Output:

[SELECT name FROM users]

Common mistake

Starting the text right after the opening quotes. A line break must follow """:

void main() {
    String text = """Hello
            """;
    IO.println(text);
}

Output:

Main.java:2: error: illegal text block open delimiter sequence, missing line terminator

Functions used in this recipe

  • String.formatted() — Uses the string itself as a template and fills it in — a shorter form of String.format().
  • Text block """ — A multi-line string literal in triple quotes.
  • String.lines() — Splits a string at line breaks and returns the lines as a stream.

Thanks for reading!

Donate to the site — we work hard for you.