Create StringBuffer object

String represents fixed-length, immutable character sequences.

StringBuffer represents growable and writeable character sequences.

StringBuffer will automatically grow to make room for such additions.

Java manipulate StringBuffers behind the scenes when you are using the overloaded + operator.

Constructors:

StringBuffer()
Creates a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
Creates a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Creates a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Creates a string buffer initialized to the contents of the specified string.

public class Main {
  public static void main(String[] argv) {
    StringBuffer sb = new StringBuffer(20);
    System.out.println(sb.capacity());
  }
}

The output:


20

Using new StringBuffer(String str)


public class Main {

  public static void main(String[] arg) {
    StringBuffer aString = new StringBuffer("ABCDE");


    String phrase = "abced";
    StringBuffer buffer = new StringBuffer(phrase);

    System.out.println(aString);
    System.out.println(buffer);
  }

}
Home 
  Java Book 
    Essential Classes  

StringBuffer:
  1. Create StringBuffer object
  2. append
  3. StringBuffer capacity()
  4. charAt(int index): get the char at specified index
  5. delete(int start, int end) and deleteCharAt(int index)
  6. ensureCapacity( )
  7. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  8. indexOf(String str)
  9. lastIndexOf(String str)
  10. StringBuffer length()
  11. Insert(): add data in the middle of a StringBuffer
  12. replace():replace a StringBuffer
  13. StringBuffer reverse()
  14. setCharAt(int index, char ch)
  15. setLength
  16. substring
  17. toString():Convert StringBuffer to String