Skip to Content

Java StringBuffer Example

  1. /*
  2.    Java StringBuffer Example
  3.    This example shows how java StringBuffer can be built and created using
  4.    different constructors of Java StringBuffer class.
  5. */
  6.  
  7.  
  8. public class JavaStringBufferExample {
  9.  
  10.   public static void main(String[] args) {
  11.     /*
  12.       Java StringBuffer is a mutable sequence of characters.
  13.       Difference between Java String and StringBuffer is that StringBuffer
  14.       can be modified while String can not.
  15.      
  16.       Java StringBuffer can buit using one of the following constructors
  17.     */
  18.    
  19.     /*
  20.     1. StringBuffer StringBuffer()
  21.     Construct empty StringBuffer with initial capacity of 16
  22.     */
  23.    
  24.     StringBuffer sbObj1 = new StringBuffer();
  25.    
  26.     /*
  27.     2. StringBuffer StringBuffer(int length)
  28.     Constructs empty StringBuffer with initial capacity of length
  29.     */
  30.     StringBuffer sbObj2 = new StringBuffer(10);
  31.    
  32.     /*
  33.     3. StringBuffer StringBuffer(String str)
  34.     constructs StringBuffer with the contents same as argument String
  35.     */
  36.     StringBuffer sbObj3 = new StringBuffer("Hello World");
  37.     System.out.println(sbObj3);
  38.    
  39.   }
  40. }
  41.  
  42. /*
  43. Output would be
  44. Hello World
  45. */