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
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – How to append a newline to StringBuffer

By Chaitanya Singh | Filed Under: StringBuffer

When we append the content to a StringBuffer object, the content gets appended to the end of sequence without any spaces and line breaks. For example:

StringBuffer sb= new StringBuffer("Hello,");
sb.append("How");
sb.append("are");
sb.append("you??");
System.out.println(sb);

This would produce this output:Hello,Howareyou??

So what if I would like to append space or new line to the buffer? Appending space is not that difficult we can simply do like this: sb.append(“ “);, however if we want to append a new line or line break then the process is bit different.

There are several ways to append a new line but most of them are platform dependent that means they work on one platform but not for other (for example appending “\r\n” would give new line on Windows but for Unix we need to append “\n”). So what is the best way to do it?
Sure, there are two platform independent ways to append a new line to the stringbuffer:

sb.append(System.getProperty("line.separator"));
sb2.append(System.lineSeparator());- This only works on jdk 1.7 or higher.

Here is the complete example

Example:

public class LineBreakStringBuffer {
   public static void main(String args[])
   {
      StringBuffer sb= new StringBuffer("Hello");
      // Method 1:
      sb.append(System.getProperty("line.separator"));
      sb.append("World");
      System.out.println(sb);
	
      StringBuffer sb2= new StringBuffer("Welcome");
      // Method 2:
      sb2.append(System.lineSeparator());
      sb2.append("to My blog");
      System.out.println(sb2);
    }
}

Output:

Hello
World
Welcome
to My blog

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 – 2022 BeginnersBook . Privacy Policy . Sitemap