Java String Handling

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 new line to StringBuilder/StringBuffer using various methods.

How to append 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 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 new line to it.

The simple version of the code will look like below.


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 API.

The Better way:

The above code is fairly simple and works. However, the 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 Unix system it is just \n.

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


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

Important Note: Since this approach uses 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 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 Unix operating system. That is because the program ran on Unix and retrieved Unix specific line separator using getProperty method.

Visit StringBuilder & StringBuffer examples to learn more. Also have a look at how to split string by new line example.