Java Multiline String – 4 Ways to Use

Here in this article, I will show you 4 different ways to use multiline strings in Java. This can be done in the following ways:

  • Text Block
  • Concatenation Operator
  • StringBuilder Class
  • Stream API and Collectors.joining()

Let’s discuss them one by one in detail with example code.

Method 1: Text Block

It is a new feature added in Java 15 version. In this example, we create a text block using triple quotes (“””). Text block is the best way to use multiline strings as the text indentation and formatting are preserved.

Output:

Method 2: Concatenation Operator

The concatenation operator (+) is used to combine various string literals. ‘\n’ escape character is used to mark the end of each line.

Output:

Method 3: StringBuilder Class

In this example, we use append() method of the StringBuilder class to append various lines of text. After that toString() method is used on the object to convert it to a multiline string.

Output:

Method 4: Stream API and Collectors.joining()

Here we defined a list of strings and used Stream API and Collectors.joining() method to join all the strings. ‘\n’ is used as a delimiter argument to indicate the end of each line.

Output:

I hope you got an idea about using the multiline strings in java. You can ask your queries in the comment section below.

Leave a Comment

Your email address will not be published. Required fields are marked *