StringBuilder in java

StringBuilder in java is like a String ,but which can be modified. It is same as StringBuffer, but only difference is that it is non-synchronized. The length of the String and content of sequence can be changed by using StringBuilder methods.

It can be implemented in following ways.

  1. StringBuilder (): creates an empty string Builder with the initial capacity of 16.
  2. StringBuilder (String str): creates a string builder with the specified string.
  3. StringBuilder (int capacity): Capacity is the no. of character it can hold.It increases automatically as more contents added to it.


It provides mutable String.

If String can be modified ,called a mutable String. It can be achieved by StringBuilder class.

Useful methods of StringBuilder :

1. append() method:

This method appends a new String into the existing String.

Output: House is beautiful

2. Length() method:

This method will give you the length of the String.

Output: 6

3. replace() method:

This method will replace substring taken its start position and end position , with  a new substring.

Output: This was a House

4. insert() method:

This method is used to insert a new String to an existing string.

Output: Yes, This is a House

5. subString() method:

It will return a substring extracted

Output: a House

from a start point.

6. Delete() method:

This will delete a part of the String mentioned in the start and end point.

Output: a House

7. reverse() method:

This method returns a reversed String.

Output: esuoH a si sihT 

8. Capacity() method:

This method  returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
StringBuffer class in java
Different ways to reverse String in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

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