Java StringBuffer class

Java String class provides several methods for ease of string manipulation. However, the String class is immutable. A string, once created, cannot grow or shrink in size. Every time we do an operation on an existing string, a new string is created that requires fresh memory allocation and garbage collection if old strings are replaced by new strings frequently. Moreover, this may also create a lot of memory fragments. To overcome these sorts of difficulties, a new peer class of String was introduced, which is StringBuffer.

StringBuffer provides many functionalities of String. Unlike String, it is mutable. It can grow and can be written into. In a StringBuffer object, we can insert characters at any index position or can delete from an index position to another index position. We will study the StringBuffer class in this article.

Constructors

StringBuffer class provides four constructors for object creation:

Constructor Description
StringBuffer() This is the default constructor. It reserves a 16 characters buffer.
StringBuffer(int size) It reserves a buffer of a given size.
StringBuffer(String str) The string argument str sets the initial content of the buffer and it reserves 16 additional characters.
StringBuffer(CharSequence chars) Creates object from the specified character sequence chars and it reserves 16 additional characters.

StringBuffer defines many methods. Many of them are similar to String methods. We will discuss some of these methods, particularly those which are specific to StringBuffer due to its mutability. 

append() Method

The append() method concatenates values to the end of the invoking StringBuffer object and returns the buffer itself. It has a single parameter – the value which is appended to the buffer. It is overloaded to accept values of all simple data types such as Objects, Strings, StringBuffer, CharSequences, and even char arrays. Some forms are:

			

StringBuffer append(int num)
StringBuffer append(String str)
StringBuffer append(Object obj)
StringBuffer append(boolean b)


				

Each call returns the StringBuffer object, and therefore the calls can be chained as shown in the code snippet below:

			

String str = "StringBuffer Object Showing append() method";
int i = 45;
boolean b = true;
double dbl = 5.62;
StringBuffer sb = new StringBuffer("This is a");
sb.append(" ").append(str).append(i).append(b).append(dbl);
System.out.println(sb);

				

This code outputs

Output:

This is a StringBuffer Object Showing append() method45true5.62 We may observe that int, boolean and double values are appended to the StringBuffer object.

insert() Method

The insert() method inserts the given value in the given index position of the StringBuffer object and returns the buffer itself. It generally has two parameters - the value to be inserted and the index where the value is to be inserted. Like, append() it is also overloaded to accept values of all the simple types, plus Strings, Objects, and CharSequences. A few of its forms are:

			

StringBuffer insert(int index, String str)
StringBuffer insert(int index, int i)
StringBuffer insert(int index, double dbl)
StringBuffer insert(int index, Object obj)

				

Here, index specifies the index at which point the string will be inserted into the invoking

StringBuffer object.

			

StringBuffer sb = new StringBuffer("This is new");
System.out.println(sb);  // before insert
sb.insert(5, "method ");
System.out.println(sb);  // after insert

				

The code snippet outputs

Output:

This is new This method is new

The string “method “ has been inserted at index position 5.

delete() Method

We can remove characters from a StringBuffer object by using the methods delete() and deleteCharAt().

			

StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int index)

				

The delete() method deletes a sequence of characters starting from the startIndex position to the endIndex-1 position and returns the resulting StringBuffer.

The deleteCharAt() method deletes a single character at the index position and returns the resulting StringBuffer. The following code snippet demonstrates this:

			

StringBuffer sb = new StringBuffer("THIS IS THIS BOOK");
System.out.println("Before delete: "+sb);
sb.deleteCharAt(8);
System.out.println("After deleting a char: " +sb);
sb.delete(8, 12);
System.out.println("After deleting the word: "+sb);

				

The output is

Output:

<p>Before delete: THIS IS THIS BOOK</p> <p>After deleting a char: THIS IS HIS BOOK</p> <p>After deleting the word: THIS IS BOOK</p>

reverse() Method

This method can be used to reverse the characters within a StringBuffer object. The method returns the resulting StringBuffer. This method has no parameters. The following code snippet demonstrates this method.

			

StringBuffer sb1 = new StringBuffer("1100230011");
System.out.println("Before Reverse: "+sb1);
System.out.println("After  Reverse: "+sb1.reverse());

				

Here is the output produced by the program:

Output:

<p>Before Reverse: 1100230011</p> <p>After&nbsp; Reverse: 1100320011</p>

length() and capacity()

StringBuffer object works around a buffer which is a chunk of memory. As soon as a StringBuffer object is created a buffer gets associated with it. The buffer size is not the length of the character sequence it holds but a little more than that. Thus, while the string has a length, the buffer has a capacity. The current length of a StringBuffer can be obtained by the length() method, while the total allocated capacity can be obtained by the capacity() method. Both length() and capacity() methods return int. We will apply these two methods to the StringBuffer objects created by the four constructor types and study the results.

			

StringBuffer sb1 = new StringBuffer();
System.out.println("Length: "+sb1.length()+"  Capacity: "+sb1.capacity());

StringBuffer sb2 = new StringBuffer("Programmming");
System.out.println("Length: "+sb2.length()+"  Capacity: "+sb2.capacity());
        
StringBuffer sb3 = new StringBuffer(50);
System.out.println("Length: "+sb3.length()+"  Capacity: "+sb3.capacity());

CharSequence cs = "Sequence";
StringBuffer sb4 = new StringBuffer(cs);
System.out.println("Length: "+sb4.length()+"  Capacity: "+sb4.capacity());
sb2.append(" is a good practice");  // length 19
System.out.println("Length: "+sb2.length()+"  Capacity: "+sb2.capacity());


				

The output of the code snippet is

Output:

Length: 0&nbsp; Capacity: 16 Length: 12&nbsp; Capacity: 28 Length: 0&nbsp; Capacity: 50 Length: 8&nbsp; Capacity: 24 Length: 31&nbsp; Capacity: 58

The output shows how StringBuffer reserves extra space for additional string modifications. In the first example, for the default constructor, 16 characters are reserved by the system, although the string length is zero. In the second example, a string of length 12 is created, and additional space for 16 characters is reserved, making the total buffer capacity 28. In the third example, a buffer of size 50 characters is created by user input. The fourth example is similar to the second. In the last example, we have appended a string of size 19. The new string is of length 31. Since the current capacity (28) is now exceeded, the capacity has now been increased to (oldcapacity*2)+2 = 58.

ensureCapacity() Method

ensureCapacity() method is used to reserve buffer space of a certain size (number of characters) after a StringBuffer object has been created. This method takes the size as a parameter and returns the resulting buffer. This is usually done when we know that we are going to append a large number of small strings to the buffer.

setLength() Method

Use setLength() to set the length of the buffer within a StringBuffer object.

void setLength(int len)

If the size of the buffer is more than the current length as returned by length(), null characters are appended to the end of the existing buffer. If the size is less than the current value returned by length(), then the characters stored after the modified length are lost.

			

StringBuffer sb = new StringBuffer();
sb.append("Java StringBuffer Class");
System.out.println("Length: "+sb.length()+" Capacity: "+sb.capacity());
    
sb.trimToSize();
System.out.println("Length: "+sb.length()+" Capacity: "+sb.capacity());
StringBuffer sb1 = new StringBuffer();
sb1.ensureCapacity(100 ); 
sb1.append("Java StringBuffer Class");
System.out.println("Length: "+sb1.length()+" Capacity: "+sb1.capacity());
StringBuffer sb2 = new StringBuffer();

sb2.ensureCapacity(100);
sb2.append("Java StringBuffer Class");
System.out.println("Length: "+sb2.length()+" Capacity: "+sb2.capacity());
sb2.setLength(25);
System.out.println("Length: "+sb2.length()+" Capacity: "+sb2.capacity());
sb2.setLength(15);
System.out.println("Length: "+sb2.length()+" Capacity: "+sb2.capacity()+"  "+sb2.toString());


				

This code produces the following output

Output:

Length: 23 Capacity: 34</p> Length: 23 Capacity: 23</p> Length: 23 Capacity: 100</p> Length: 23 Capacity: 100</p> Length: 25 Capacity: 100</p> Length: 15 Capacity: 100&nbsp; Java StringBuffer