Java – Need for StringBuffer and Important Constructors of StringBuffer Class | Code Factory


Index Page : Link

Donate : Link

Medium Link : Link

Applications : Link

  • If content is fixed, not changed frequently or not changed then go for String.
  • If content is not fixed and keep on changing then never used String concepts, use StringBuffer.

1. StringBuffer sb = new StringBuffer()

– Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

– If more characters is added then like collections it will create new object with more capacity and object reference is to the new object.

new capacity = (cc + 1) * 2
             = (16 + 1) * 2 = 34
             = (34 + 1) * 2 = 70
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // 16
sb.append("abcdefghijklmnop");
System.out.println(sb.capacity()); // 16
sb.append("q");
System.out.println(sb.capacity()); // 34

2. StringBuffer sb = new StringBuffer(int capacity)

– Constructs a string buffer with no characters in it and the specified initial capacity.

– Throws: NegativeArraySizeException – if the capacity argument is less than 0.

StringBuffer sb = new StringBuffer(100);
System.out.println(sb.capacity()); // 202

/*
at 101th char capacity = (100 + 1) * 2
                       = 202
*/

3. StringBuffer sb = new StringBuffer(String str)

– Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.

StringBuffer sb = new StringBuffer("Code");
System.out.println(sb.capacity()); // 20

/*
capacity = s.length() * 16
         = 4 + 16
         = 20
*/

5 thoughts on “Java – Need for StringBuffer and Important Constructors of StringBuffer Class | Code Factory”

Leave a comment