Way2Java

StringBuffer Constructors Example

StringBuffer is mutable and String is immutable. To modify the string present in the buffer, many methods are defined in StringBuffer class.

Apart methods, there are 4 types of StringBuffer Constructorsas on Java SE 7.
  1. public StringBuffer()
  2. public StringBuffer(int initialCapacity)
  3. public StringBuffer(String str)
  4. public StringBuffer(CharSequence seq)
Let us see what Java API says about StringBuffer Constructors:
  1. public StringBuffer(): Creates a StringBuffer object with an empty string placed in the buffer initially with a buffer capacity of 16 characters to store.
  2. public StringBuffer(int initialCapacity): Creates a StringBuffer object with an empty string placed in the buffer initially with a buffer capacity of initialCapacity.
  3. public StringBuffer(String str): Creates a StringBuffer object with string str placed in the buffer initially with a buffer capacity of 16 + str.length().
  4. public StringBuffer(CharSequence seq): Creates a StringBuffer object with CharSequence seq placed in the buffer initially with a buffer capacity of 16 + seq.length().
We use two methods in the example code.
  1. capacity(): Returns the buffer storing capacity as an int value. Initially the default constructor creates 16 buffer capacity and increases automatically when the buffer gets filled up with string. Programmer can place extra data in the buffer with append() method.
  2. length(): Returns the number of characters present in the buffer as an int value. By common sense also you can say, buffer length (number of characters present) cannot be more than the buffer capacity.

Let us illustrate the length and capacities through an example.

Following example illustrates the usage of 4 types of StringBuffer Constructors.
public class Demo
{
  public static void main(String args[])
  {
   StringBuffer sb1 = new StringBuffer();
   System.out.println("sb1 length: " + sb1.length());      // prints 0 as there is not data in the buffer
   System.out.println("sb1 capacity: " + sb1.capacity());  // prints 16, the default capacity

   StringBuffer sb2 = new StringBuffer(50);
   System.out.println("sb2 length: " + sb2.length());      // prints 0 as there is not data in the buffer
   System.out.println("sb2 capacity: " + sb2.capacity());  // prints 50

   String str1 = "hello";
   StringBuffer sb3 = new StringBuffer(str1);
   System.out.println("sb3 length: " + sb3.length());      // prints 5, the length of hello
   System.out.println("sb3 capacity: " + sb3.capacity());  // prints 22; str1.length()+16

   CharSequence seq1 = "hello";
   StringBuffer sb4 = new StringBuffer(seq1);
   System.out.println("sb4 length: " + sb4.length());      // prints 5, the length of hello
   System.out.println("sb4 capacity: " + sb4.capacity());  // prints 22; str1.length()+16
 }
}



Screenshot on StringBuffer Constructors Example

Would you like to know 9 types of String constructors?