How to append new line in StringBuffer - Java Language Basics

Java examples for Language Basics:StringBuffer

Introduction

To append new line to StringBuffer, use append method of StringBuffer class.

Different operating systems uses different escape characters to denote new line.

For example, in Windows and DOS it is \r\n, in Unix it is \n.

To write code which works in all OS, use Java System property line.separator instead of escape characters.

Demo Code

public class Main {
       //from   w w w . j av a 2 s .  c o m
        public static void main(String args[]){
                //create StringBuffer object
                StringBuffer sbf = new StringBuffer("This is the first line.");
               
                sbf.append(System.getProperty("line.separator"));
                sbf.append("This is second line.");
               
                System.out.println(sbf);
        }
}

Result


Related Tutorials