Skip to Content

Java StringBuffer append new line example

  1. /*
  2.         Java StringBuffer append new line example
  3.         This example shows how to append new line in StringBuffer in Java using
  4.         append method.
  5. */
  6.  
  7. public class JavaStringBufferAppendNewLineExample {
  8.        
  9.         public static void main(String args[]){
  10.                
  11.                 //create StringBuffer object
  12.                 StringBuffer sbf = new StringBuffer("This is the first line.");
  13.                
  14.                 /*
  15.                  * To append new line to StringBuffer in Java, use
  16.                  * append method of StringBuffer class.
  17.                  *
  18.                  * Different operating systems uses different escape characters to
  19.                  * denote new line. For example, in Windows and DOS it is \r\n, in Unix
  20.                  * it is \n.
  21.                  *
  22.                  * In order to write code which works in all OS, use Java System property
  23.                  * line.separator instead of escape characters.
  24.                  */
  25.                
  26.                 sbf.append(System.getProperty("line.separator"));
  27.                 sbf.append("This is second line.");
  28.                
  29.                 System.out.println(sbf);
  30.                
  31.         }
  32. }
  33.  
  34. /*
  35. Output of above given StringBuffer append new line Java example would be,
  36. This is the first line.
  37. This is second line.
  38. */