StringBuffer Constructors Example

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.


StringBuffer Constructors
Screenshot on StringBuffer Constructors Example

Would you like to know 9 types of String constructors?

Leave a Reply

Your email address will not be published. Required fields are marked *