Java Multi-line String

1. Overview

In this article, we’ll learn how to declare multi-line strings in Java.
Now that Java 15 is out, we can use the new native feature called Text blocks.
We’ll also review other methods if we can’t use this feature.

2. Text Blocks

We can use Text Blocks by declaring the string with  “”” (three double-quote marks):

public String textBlocks() {
    return """
        Get busy living
        or
        get busy dying.
        --Stephen King""";
}

It is, by far, the most convenient way to declare a multi-line string. Indeed, we don’t have to deal with line separators or indentation spaces, as we can read in our dedicated article.

This feature is available in Java 15, but also Java 13 and 14 if we enable the preview feature.

In the following chapters, we’ll review other methods suitable if we use a previous version of Java or if Text blocks aren’t applicable.

3. Getting the Line Separator

Each operating system can have its own way of defining and recognizing new lines. In Java, it’s very easy to get the operating system line separator:

String newLine = System.getProperty("line.separator");

We’re going to use this newLine in the following sections to create multi-line strings.

4. String Concatenation

String concatenation is an easy native method which can be used to create multi-line strings:

public String stringConcatenation() {
    return "Get busy living"
            .concat(newLine)
            .concat("or")
            .concat(newLine)
            .concat("get busy dying.")
            .concat(newLine)
            .concat("--Stephen King");
}

Using the + operator is another way of achieving the same thing. Java compilers translate concat() and the + operator in the same way:

public String stringConcatenation() {
    return "Get busy living"
            + newLine
            + "or"
            + newLine
            + "get busy dying."
            + newLine
            + "--Stephen King";
}

5. String Join

Java 8 introduced String#join, which takes a delimiter along with some strings as arguments. It returns a final string having all input strings joined together with the delimiter:

public String stringJoin() {
    return String.join(newLine,
                       "Get busy living",
                       "or",
                       "get busy dying.",
                       "--Stephen King");
}

6. String Builder

StringBuilder is a helper class to build Strings. StringBuilder was introduced in Java 1.5 as a replacement for StringBuffer. It’s a good choice for building huge strings in a loop:

public String stringBuilder() {
    return new StringBuilder()
            .append("Get busy living")
            .append(newLine)
            .append("or")
            .append(newLine)
            .append("get busy dying.")
            .append(newLine)
            .append("--Stephen King")
            .toString();
}

7. String Writer

StringWriter is another method that we can utilize to create a multi-line string. We don’t need newLine here, because we use PrintWriter. The println function automatically adds new lines:

public String stringWriter() {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    printWriter.println("Get busy living");
    printWriter.println("or");
    printWriter.println("get busy dying.");
    printWriter.println("--Stephen King");
    return stringWriter.toString();
}

8. Guava Joiner

Using an external library just for a simple task like this doesn’t make much sense, however, if the project already uses the library for other purposes, we can utilize it. For example, Google’s Guava library is very popular. Guava has a Joiner class that is able to build multi-line strings:

public String guavaJoiner() {
    return Joiner.on(newLine).join(ImmutableList.of("Get busy living",
        "or",
        "get busy dying.",
        "--Stephen King"));
}

9. Loading from a File

Java reads files exactly as they are. This means that if we have a multi-line string in a text file, we’ll have the same string when we read the file. There are a lot of ways to read from a file in Java.

Actually, it’s a good practice to separate long strings from code:

public String loadFromFile() throws IOException {
    return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt")));
}

10. Using IDE Features

Many modern IDEs support multi-line copy/paste. Eclipse and IntelliJ IDEA are examples of such IDEs. We can simply copy our multi-line string and paste in inside two double quotes in these IDEs.

Obviously, this method doesn’t work for string creation in run time, but it’s a quick and easy way to get a multi-line string.

11. Conclusion

In this tutorial, we learned several methods to build multi-line strings in Java.

The good news is Java 15 has native support for multi-line strings via Text Blocks.

All the other methods reviewed can be used in Java 15 or any previous version.

The code for all the methods in this article is available over on Github.

Related posts:

Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
The Guide to RestTemplate
Allow user:password in URL
Giới thiệu Json Web Token (JWT)
Spring Boot - Runners
Handling URL Encoded Form Data in Spring REST
HttpClient Connection Management
Java Program to Perform String Matching Using String Library
Spring Boot - OAuth2 with JWT
Java Program to Implement Levenshtein Distance Computing Algorithm
Java Program to find the maximum subarray sum using Binary Search approach
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Check for balanced parenthesis by using Stacks
Java Program to Represent Graph Using Incidence List
Mapping a Dynamic JSON Object with Jackson
Java Program to Represent Graph Using Linked List
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
Spring Boot - Application Properties
Spring Boot - Zuul Proxy Server and Routing
Java Program to Generate a Random Subset by Coin Flipping
Beans and Dependency Injection
Spring Boot - Logging
Java Program to Solve a Matching Problem for a Given Specific Case
Multipart Upload with HttpClient 4
How to Define a Spring Boot Filter?
Java Program to Implement Maximum Length Chain of Pairs
A Guide to Iterator in Java
Guide to Guava Multimap
Write/Read cookies using HTTP and Read a file from the internet
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
TreeSet và sử dụng Comparable, Comparator trong java
Java Program to Print only Odd Numbered Levels of a Tree