Java Multiline String (with Examples)

Multiline strings allow the creation of string literals that span several lines of source code. Writing multi-line strings in Java can be approached differently depending on the version of Java you are using.

For example, Java 15 (and later) has native support for multiline strings via Text Blocks. Before Java 15, String concatenation was the most commonly used for creating multiline strings.

Java VersionPreferred Method for Creating Multiline Strings
Java 15 and LaterText Blocks
Java 8 to Java 14String.join(), StringJoiner, or Collectors.joining()
Before Java 8String Concatenation

Let’s explore how to write multi-line strings in both Java 8 and Java 15 onwards.

1. Multiline Strings with Text Blocks [Java 15+]

Java text blocks were included in Java 13 (JEP 355) and Java 14 (JEP 368) as preview features. It has become a standard feature in Java 15 (JEP 378). The text block is concise, easy to update, and easy to understand.

The syntax of text blocks is quite straightforward.

  • A text block comprises multiple lines of text and uses three double-quote characters (“””) as the opening and closing delimiters.
  • The opening three double-quote characters are always followed by a line terminator. Content has to start on the next line only.
  • The closing three double-quote characters can be in a separate line or added to the last appended line.
  • If the text content contains single or double quotes, there is no need to escape them.

Let’s quickly see how text blocks form a multiline string:

String content = """
    Line 1
    'Line 2'
    "Line 3"
    Line 4 
    """;

System.out.println(content);

Program output:

Line 1
'Line 2'
"Line 3"
Line 4

With text blocks, you simply write the string in the source code as it should appear, including new lines and any necessary indentation. This feature significantly improves code readability and maintainability, especially when dealing with large strings or ones that need to preserve formatting, like SQL queries or JSON data.

String json = """
    {
      "name": "John Doe",
      "age": 30,
      "city": "New York"
    }
    """;

System.out.println(json);

Program output:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}

2. Multiline Strings Before Java 15

Before Java 15, there was not any direct support to represent the multiline strings, so programmers created their ways to create such strings over time. Let us look at a few of them.

2.1. String Concatenation

Before text blocks, probably the most common approach relies on straightforward concatenation via the well-known “+” operator.

String content = "Line 1" +
    NEW_LINE +
    "'Line 2'" +
    NEW_LINE +
    "\"Line 3\"" +
    NEW_LINE +
    "Line 4 ";

System.out.println(content);

Note that modern Java compilers use StringBuilder or StringBuffer under the hood if there are multiple strings being combined in a loop or a similar scenario. So internally, the compiler may transform it into something similar to:


StringBuffer sb = new StringBuffer();

String content = sb.append("Line 1")
    .append(NEW_LINE)
    .append("'Line 2'")
    .append(NEW_LINE)
    .append("\"Line 3\"")
    .append(NEW_LINE)
    .append("Line 4 ").toString();

2.2. String Join

Starting with JDK 8, we can use the String.join() method to represent multiline strings. The best part of the join() method is that it takes as the first argument a delimiter, and it uses this delimiter between the strings that will be concatenated.

String content = String.join(NEW_LINE,
    "Line 1",
    "'Line 2'",
    "\"Line 3\"",
    "Line 4 ");

System.out.println(content);

Another way to join strings, since Java 8, is StringJoiner class. A StringJoiner supports a delimiter (as String.join()) but also supports a prefix and a suffix. However, the prefix/suffix may not be needed in multiline strings.

2.3. Java Streams

If we have the strings in a collection, such as List or Set, then it makes sense to use the Stream API for joining the strings using the Collectors.joining() collector. This collector works as String.join(), and in our case, it looks as follows:

String content = Stream.of("Line 1", "'Line 2'", "\"Line 3\"", "Line 4 ")
    .collect(Collectors.joining(NEW_LINE));

System.out.println(content);

3. Conclusion

The decision to choose, how to create multiline strings, largely depends on the Java version we are using. If we are using Java 15 or later, then there is no reason to not use the Text Blocks. Before Java 15, String concatenation was a preferred method until the introduction of StringJoiner and Stream API.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.