beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to append a newline to StringBuilder

By Chaitanya Singh | Filed Under: StringBuilder

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.

Enjoyed this post? Try these related posts

  1. Difference between StringBuilder and StringBuffer
  2. StringBuilder append() null values as “null” String

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap