StringBuffer class in java

StringBuffer class in java is like a String ,but which can be modified. The length of the String and content of sequence can be changed by using StringBuffer methods.

It can be implemented in following ways.

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

Important point to note:

Note: StringBuffer class is thread-safe i.e. can not be accessed by multiple threads at a time but in a order.

It provides mutable String.

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

Useful methods of StringBuffer:

1. StringBuffer 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
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
String methods - matches and regionMatches
StringBuilder in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

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