Skip to content

Java StringBuilder Append New Line Example (StringBuffer)

Java StringBuilder append new line example shows how to append new line in StringBuilder or StringBuffer object. It also shows how to add a new line to StringBuilder/StringBuffer using various methods.

How to append a new line in StringBuilder or StringBuffer in Java?

Many times we use StringBuilder or StringBuffer to create and store multiline content or text. In such cases, we want to append or add a new line to the StringBuilder content.

The StringBuilder or StringBuffer class does not provide any direct method to append a new line to the content. However, you can utilize the overloaded String version of the append method of StringBuilder/StringBuffer class to append a new line to it.

The simple version of the code will look like below.

Output

As you can see from the output when we print the content of the StringBuilder object we can see two lines in the output. The same code works for the StringBuffer as well because they both have similar APIs.

What is the better way to append a new line?

The above code is fairly simple and works. However, a better approach is to use system property instead of using \n. The new line is represented differently in different operating systems. For Windows, new line is \r (carriage return) followed by \n i.e. \r\n. However, in the Unix system, it is just \n.

Because of this difference at the operating system level, the above code might not work in any particular OS. For this reason, the Java System class provides getProperty method to retrieve system specific line separator. The “line.separator” property returns the system-specific line separator.

Output

The above code now works in all the operating systems as it does not hard code \n but uses a system-specific line separator instead.

Important Note: Since this approach uses an operating system-specific new line, it makes the final output non-portable, if there is any.

For example, suppose your code uses StringBuilder to generate the multiline content and finally writes to a file in the Unix operating system. Now if you try to read the same file in Windows, the file might be missing new lines as it has new line character(s) of the Unix operating system. That is because the program ran on Unix and retrieved Unix specific line separator using getProperty method.

Also, have a look at how to split string by new line example.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

About the author

Leave a Reply

Your email address will not be published.