There are following two ways to append a new Line to a StringBuilder object:
1) StringBuilder.append("\n");
2) StringBuilder.append(System.getProperty("line.separator"));
Example
In this example we have a StringBuilder object sb and we have demonstrated both the methods of adding a new line.
class AddNewLineDemo{
public static void main(String args[]){
// Create StringBuilder object
StringBuilder sb = new StringBuilder("String1 - ");
// Appending a String to StringBuilder
sb.append("String2 - ");
// Method 1: Add new Line using append() method
sb.append("\n");
// Again Appending a new String
sb.append("String3 - ");
// Method 2: Add new Line using System.getProperty()
sb.append(System.getProperty("line.separator"));
//Adding few more Strings
sb.append("String4 - ");
sb.append("String5 - ");
// Displaying the output
System.out.println(sb);
}
}
Output:
String1 - String2 - String3 - String4 - String5 -
Note: While using method 1 take care of the slash, \n will work but /n will not work.
Recommended Post: StringBuilder in Java
Leave a Reply