Java multi-line string, text blocks

This article will show you a few ways to declare and use a multi-line string in Java.

  1. String + String + String
  2. StringBuilder
  3. String.format
  4. StringWriter
  5. String.join (Java 8)
  6. Files.lines (Java 8)
  7. (""") Java 13 and Java 14 text blocks (preview feature)

Review an HTML and a JSON string, and we will use the above methods to declare the following multi-line string in Java.


<html>
    <body>
        <p>Hello, World</p>
    </body>
</html>

{
    "name":"mkyong",
    "age":38
}

1. String + String + String

The simplest solution, add a multi-line string with +.

MultiLineString1.java

    String html = "<html>\n"
                + "     <body>\n"
                + "         <p>Hello, World</p>\n"
                + "     </body>\n"
                + "</html>";

    String json = "{\n"
                + "     \"name\":\"mkyong\",\n"
                + "     \"age\":38\n"
                + "}";

2. String Builder

This method is a commonly used pattern.

MultiLineString2.java

    String html = new StringBuilder()
            .append("<html>\n")
            .append("     <body>\n")
            .append("         <p>Hello, World</p>\n")
            .append("     </body>\n")
            .append("</html>")
            .toString();

    String json = new StringBuilder()
            .append("{\n")
            .append("     \"name\":\"mkyong\",\n")
            .append("     \"age\":38\n")
            .append("}").toString();

3. String Format

It works, but not recommend, it is too hard to count the number of %s.

MultiLineString3.java

    String html = String.format("%s\n%s\n%s\n%s\n%s"
            , "<html>"
            , "     <body>"
            , "         <p>Hello, World</p>"
            , "     </body>"
            , "</html>");

    String json = String.format("%s\n%s\n%s\n%s"
            , "{"
            , "     \"name\":\"mkyong\","
            , "     \"age\":38"
            , "}");

4. String Writer

A bit weird, but it works.

MultiLineString4.java

    // no need close this
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.println("<html>");
    pw.println("     <body>");
    pw.println("         <p>Hello, World</p>");
    pw.println("     </body>");
    pw.println("</html>");
    String html = sw.toString();

    StringWriter sw2 = new StringWriter();
    PrintWriter pw2 = new PrintWriter(sw2);
    pw2.println("{");
    pw2.println("    \"name\":\"mkyong\",");
    pw2.println("    \"age\":38");
    pw2.println("}");
    String json = sw2.toString();

5. Java 8 String.join

Java 8, joins multi-lines string with a new line.

MultiLineString5.java

    String html = String.join("\n"
                , "<html>"
                , "     <body>"
                , "         <p>Hello, World</p>"
                , "     </body>"
                , "</html>");

    String json = String.join("\n"
                , "{"
                , "    \"name\":\"mkyong\","
                , "    \"age\":38"
                , "}");

6. Files.lines

It is common to put a multi-line string into a file. This example uses Files.lines to load a file from a classpath resources folder, and convert it into a Stream<String> for processing.

resources/test.html

<html>
    <body>
        <p>Hello, World</p>
    </body>
</html>
MultiLineString6.java

package com.mkyong.java13.jep355;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MultiLineString6 {

    public static void main(String[] args) throws IOException, URISyntaxException {

        Stream<String> lines = Files.lines(
                Paths.get(ClassLoader.getSystemResource("test.html").toURI())
        );

        System.out.println(lines.collect(Collectors.joining("\n")));

    }
}

Output

Terminal

<html>
    <body>
        <p>Hello, World</p>
    </body>
</html>

7. Text Blocks (Preview in Java 13, 14)

7.1 Now, we can use three double-quote characters (""") to declare multi-line string in Java. This text block is the recommended solution, simple and beautiful, hope it will become a standard feature soon.

P.S This text blocks is a preview feature in Java 13 and Java 14, it might change again in a future release.

TextBlockExample.java

    String html =   """
                    <html>
                        <body>
                            <p>Hello, World</p>
                        </body>
                    </html>
                    """;

    String json =   """
                    {
                        "name":"mkyong",
                        "age":38
                    }
                    """;

This text blocks:


"""
line 1
line 2
line 3
"""

is equivalent to this:


"line 1\nline 2\nline 3\n"

7.2 This text block supports escape sequences.


    String html = """
                  <html>
                  \t<body>
                  \t\t<p>Hello, World</p>
                  \t</body>
                  </html>
                  """;

7.3 The quote characters (") can be used inside a text block; see this multi-lines JSON formatted string.


    String json =   """
                    {
                        "name":"mkyong",
                        "age":38
                    }
                    """;

7.4 Concatenation of text blocks, below is a valid syntax.


  String html = "<html>\n" +
                """
                    <body>
                        <p>Hello, World</p>
                    </body>
                """+
                "</html>";

7.5 In Java 13, three methods added to support text blocks.

  • String::stripIndent(): Strip away incidental white space from the text block content.
  • String::translateEscapes(): Translate escape sequences.
  • String::formatted(Object... args): For value substitution in the text block.

The String::formatted example for value substitution in a text block.


  String json =   """
                  {
                      "name":"%s",
                      "age":%d,
                      "address":"%s"
                  }
                  """;
  System.out.println(json.formatted("mkyong", 38, "abc"));

We can get the same result with the standard String::replace or String.format like this:


  // String.format
  String json = """
                {
                    "name":"%s",
                    "age":%d,
                    "address":"%s"
                }
                """;

  System.out.println(String.format(json, "mkyong", 38, "abc"));

  // String::replace
  String json2 =   """
                  {
                      "name":"$name",
                      "age":$age,
                      "address":"$address"
                  }
                  """;

  System.out.println(json2
          .replace("$name", "mkyong")
          .replace("$age", "38")
          .replace("$address", "abc"));

Do we need a new API String::formatted(Object... args) for value substitution?

7.6 In Java 14, two methods added to support text blocks.

  • \<end-of-line> suppresses the line termination.
  • \s is translated into a single space.

  String html = """
                <html>
                    <body>\
                        <p>Hello, '\s' World</p>\
                    </body>
                </html>
                """;

Output

Terminal

<html>
    <body>        <p>Hello, ' ' World</p>    </body>
</html>

7.7 Java 15 (not released yet), to be continued.

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-13
$ cd java-14

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar