Java | StringBuffer Class

05 min read

StringBuffer Class:

  • Represents growable character sequences.
  • A character or substring may be inserted in the middle or appended to the end.
  • StringBuffer will automatically grow to make room for such additions.

Constructors:

1. StringBuffer( )

  • Reallocation should not happen quite frequently for 2 reasons
  • StringBuffer does not allocate space for each character (as it comes) individually. Rather, it allocates space for a few extra characters and thus reduces the number of reallocations that take place.
  • Reserves space for 16 characters, without reallocation. 
    • It is a costly process in terms of time.
    • Frequent reallocations can fragment memory.
  • For each reallocation, the capacity is increased to twice the current capacity +2.

StringBuffer sb=new StringBuffer(10);

This creates a StringBuffer object which can hold 16 characters and will go for reallocation if more characters are added. Its reference is stored in the reference variable.

 

2.StringBuffer(int size)

  • Sets the default size specified by 'size' instead of 16.

StringBuffer sb=new StringBuffer(10);

The initial capacity of the object is 10 characters.

 

3. StringBuffer(String str)

  • StringBuffer object is created from the existing string 1st? and reserves room for 16 more characters without reallocation.

 

4.StringBuffer(CharSequence chars)

  • Creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error