This post will discuss how to create multiline strings in Java.

1. Using String concat (+)

A simple solution to concat strings that span multiple lines is using the String concatenation operator (+). This approach can be used if string concatenation does not take place within a loop, since the compiler optimizes the string concatenation using the + operator.

This is demonstrated below. Note that each line is terminated by \n. If you need the system-dependent line separator string, use the System.lineSeparator() method.

Download  Run Code

Output:

Line 1
Line 2
Line 3

 
If you’re using IntelliJ IDEA, you don’t have to manually write the complete string. IntelliJ IDEA automatically adds "..\n" + for all lines when you paste the multiline string within "". In Eclipse, this option is not enabled by default. To enable it, just select “Escape text when pasting into a string literal” in Window -> preferences -> java -> Editor -> Typing.

2. Using StringBuilder

You should consider using the StringBuilder over the String concat operator (+) if the multiline string is constructed within a loop.

Download  Run Code

Output:

Line 1
Line 2
Line 3

3. Using String.format() method

If you have less number of lines in the multiline string, consider using the String.format() method that returns a formatted string according to the specified format arguments. For instance,

Download  Run Code

Output:

Line 1
Line 2
Line 3

4. Using String.join() method

Starting with Java 8, you can use the String.join() method that returns a new String composed of specified strings joined together with a copy of the specified delimiter. For example,

Download  Run Code

Output:

Line 1
Line 2
Line 3

5. Java 13 – Using Text Blocks

There is no direct option to create a multiline string literal in Java 12 or less. Java 13, however, allows you to define multiline string literals using text blocks with ease. Note that text blocks are a preview feature and are disabled by default. You can use --enable-preview to enable text blocks.

Download Code

Output:

Line 1
Line 2
Line 3

That’s all about creating multiline strings in Java.