StringBuffer class in Java

StringBuffer class is a mutable class, unlike the String class which is immutable. As we know that String objects are immutable, so if we do a lot of changes with String objects, we will end up with a lot of memory leak.

So StringBuffer class is used when we have to make a lot of modifications to our string. It is also threaded safe i.e multiple threads cannot access it simultaneously.

StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).

 

Mutable StringA string that can be modified is known as the mutable string. StringBuffer class is used for creating the mutable string.

 

Constructors in StringBuffer class

StringBuffer class define 3 constructors.

  1. StringBuffer ()
  2. StringBuffer (int size)
  3. StringBuffer (String str)

 

Example to express difference between String and StringBuffer

In the below example we are modifying String object str and StringBuffer object sb and we can see str is not modified.

Output:

Selenium
SeleniumBix

 

Automation Testing Video Tutorial:

 

Methods in the StringBuffer Class

There are many methods in the StringBuffer class. Let’s see important methods with example-

 

1. append() method – This method will concatenate the given argument with this string. append() method has several overloaded forms.

Output:

Selenium12345

 

2. insert() method – The insert() method inserts the given string with this string at the given position.

Output:

EasBixy

 

3. reverse() method – The reverse() method reverses the characters of the String.

Output:

yasE

 

4. replace() method – The replace() method replaces the string from specified start index to the end index.

Output:

EBix

 

5. capacity() method – The capacity() method of StringBuffer class 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.

Output:

16

48

 

0 Comment

Leave a Reply