Skip to content

Java StringBuffer Tutorial with Examples

Java StringBuffer tutorial with examples will help you understand how to use the Java StringBuffer class in an easy way. StringBuffer in Java is a mutable sequence of characters. The difference between String and StringBuffer is that the StringBuffer is mutable while String is immutable. it means that the StringBuffer object’s content can be changed or modified using its methods.

The StringBuffer class in Java is a thread-safe implementation, which means that if multiple threads are trying to modify the contents of the string buffer at the same time, the StringBuffer class takes care of the synchronization.

The Java StringBuffer class extends from the Object class and implements Serializable, Appendable, and CharSequence interfaces. It is contained in the java.lang package. The java.lang package is automatically imported into the code, so you do not have to import any package to use the StringBuffer class.

How to create a new StringBuffer object?

The StringBuffer class in Java provides several constructors to create new objects. The default constructor creates a new empty StringBuffer object with the initial capacity of 16.

If you want to create a StringBuffer object from the existing object of String, StringBuffer, or StringBuilder class, use the constructor with the CharSequence argument.

Output

The capacity of the StringBuffer object will be 16 + the length of the character sequence given in the argument.

How to get StringBuffer length using the length method?

The length method of the StringBuffer class returns the number of characters currently stored in the object.

Output

How to set StringBuffer length using the setLength method?

The setLength method sets the length of the character sequence of this StringBuffer object.

If the new length is greater than or equal to the current length of the StringBuffer, then ‘\u0000’ (null characters) is appended at the end of the character sequence so that the current length becomes the new length. If the new length is less than the current length, the current length is changed to the new length by discarding the characters from the end.

Output

How to append content to the StringBuffer object using the append method?

The append method appends the specified argument at the end of the StringBuffer content. The append method is overloaded to accept char, char array, boolean, CharSequence, double, float, int, long, Object, String, and StringBuffer types.

Output

How to append a substring of String to StringBuffer object?

The above given example appends the full content of the String or StringBuffer object to another StringBuffer object. If you want to append a substring instead of the full string, use the below given overloaded append method.

This method appends the content of the specified objects substring starting from the start index and ending at the end index to this StringBuffer object. Since this method accepts the CharSequence reference, you can use String, StringBuffer, or StringBuilder object. Plus, the start index is inclusive, while the end index is exclusive.

Example:

Output

How to insert content into the StringBuffer object using the insert method?

The insert method of the StringBuffer class inserts the specified argument string at the given index of the StringBuffer object. Just like the append method, the insert method is also overloaded for boolean, char, char array, CharSequence, double, float, int, long, and String types. Let’s have a look at the insert method with the String argument.

This method inserts the string into the StringBuffer at the specified index.

Output

If you want to insert the substring of String, StringBuffer, or StringBuilder object into the StringBuffer, use below given overloaded insert method.

This method inserts the substring of the specified CharSequence starting from the start and ending at the end index to this StringBuffer object at the specified index. The start index is inclusive, while the end index is exclusive.

Output

How to get a character from the StringBuffer using the charAt method?

The charAt method of the StringBuffer class returns a character stored at the specified index of the StringBuffer object. The index is 0 based, so the first character is at index 0 and the last character is located at StringBuffer length – 1 index.

Output

The charAt method throws IndexOutOfBoundsException if the given index is negative or is greater than or equal to the length of the StringBuffer object.

How to replace a character in the StringBuffer object using the setCharAt method?

The setCharAt method replaces a character at the specified index with the given new replacement character.

Output

The setCharAt method throws IndexOutOfBoundsException if the specified index is negative or is greater than or equal to StringBuffer length.

How to replace a substring in StringBuffer using the replace method?

The replace method replaces the substring of this StringBuffer with the specified replacement string.

The start index is inclusive and the endIndex is exclusive i.e. the replacement starts at the startIndex and ends at endIndex – 1.

Example:

Output

The replace method throws StringIndexOutOfBoundsException if the startIndex is negative, or greater than the length of the StringBuffer, or greater than the endIndex.

How to get a substring from StringBuffer using the substring method?

The substring method returns a new String object containing the subsequence starting at the specified index to the end of the StringBuffer content.

Example:

Output

The above method gets the substring starting from the specified index and ending at the StringBuffer’s length. If you want to get the substring starting and ending at the specified index, use an overloaded substring method having start and end index parameters.

Output

This method throws IndexOutOfBoundsException if the start or end index is negative or greater than the length, or the start index is greater than the end index.

How to get a substring from StringBuffer using the subSequence method?

The subSequence method returns a new character sequence that is a subsequence of this StringBuffer object, starting and ending at the specified index.

This method is exactly the same as the substring method except for the return type. The substring method returns a String object while the subSequence method returns a CharSequence. The subSequence method is provided just because the StringBuffer class implements the CharSequence interface.

Output

How to delete a character or substring from the StringBuffer?

1. How to delete a character from the StringBuffer using the deleteCharAt method?

The deleteCharAt method deletes a character from the StringBuffer at the specified index.

Output

This method throws StringIndexOutOfBoundsException if the index is negative or greater than or equal to the StringBuffer length.

2. How to delete a substring from the StringBuffer using the delete method?

The delete method deletes a substring from the StringBuffer starting and ending at the specified index.

The substring starts with the startIndex and ends at endIndex – 1. This method also throws StringIndexOutOfBoundsException if the startIndex is negative or is greater than the endIndex.

Output

3. How to empty the StringBuffer (delete all characters)?

The StringBuffer class in Java does not provide any direct method using which you can empty the StringBuffer object. However, you can use the delete method and specify 0 as the start index and StringBuffer length – 1 as the end index to remove all the characters from the StringBuffer.

Output

Please visit the StringBuilder empty or clear example to know more.

How to search substring in the StringBuffer using indexOf and lastIndexOf methods?

The indexOf method returns the index of the specified substring within this StringBuffer object. If the substring is not found within the StringBuffer, it returns -1.

Example:

Output

The above-given method starts searching for the specified substring from index 0. If you want to search the substring from the specified start index, use an overloaded indexOf method with the start index argument.

Output

Both of these indexOf methods return the index of the first occurrence of the specified substring. If you want to search for the last occurrence of the substring, use lastIndexOf method. The lastIndexOf method searches for the substring in the backward direction (from end to start of the StringBuffer).

Output

Similarly, you can also specify the start index from where you want to search for the last occurrence using an overloaded lastIndexOf method with the start index parameter.

How to reverse the StringBuffer?

The reverse method replaces the StringBuffer content with the reversed content (StringBuffer reverse).

Output

How to convert StringBuffer to String object?

The toString method of the StringBuffer class returns a new String object containing the character sequence of this object.

Output

What is a StringBuffer capacity?

The StringBuffer in Java internally manages an array, also called a buffer, to store its content or character sequence. The length of this internal array is called StringBuffer capacity. The capacity of the StringBuffer is automatically increased as we add more content to it. It does it by allocating a new internal array with the required length when the existing internal buffer overflows.

Allocating a new array is a costly operation. If you know the approximate number of the character the StringBuffer object is going to hold beforehand, you should create the StringBuffer object with the required capacity using the below constructor.

This will avoid allocating and copying the content to the new internal array and will improve the performance of the code.

How to know the current capacity of the StringBuffer object using the capacity method?

The capacity method returns the current capacity of the internal buffer. Its the amount of storage that is available to store the characters. If the content length to be inserted or appended to this StringBuffer object is greater than the current capacity, a new array allocation will occur to fit the new content.

Output

As you can see from the output, if we try to put content into StringBuffer having more characters than the current capacity, the capacity will be automatically increased.

How to create a StringBuffer object with a given minimum capacity?

Why do we need to ensure the capacity of the StringBuffer? Well, as we have seen in the above example, a new array needs to be allocated in case the current capacity is not large enough to fit the content. The array allocation is a costly operation involving two steps. First, the memory needs to be allocated for the new array, and second, the existing content of the buffer array needs to be copied to the newly allocated array.

We can avoid this performance penalty if we know the approximate number of characters the StringBuffer is going to hold and create the StringBuffer with the required capacity. There are two ways to do this, first using the constructor with the capacity argument which we have already seen, and second using the ensureCapacity method to reduce it.

The ensureCapacity method ensures that the buffer is at least equal to the given minimum capacity. If the current capacity is less than the given minimum capacity, a new array is allocated with the capacity which is larger of the specified capacity or (old capacity * 2 ) + 2.

Output

How to reclaim the unused capacity using the trimToSize method?

In many cases, after some processing, we do not need the StringBuffer with a large capacity. Consider below given example.

Output

As you can see from the output, even after emptying the StringBuffer object, the capacity of the StringBuffer object remains the same. If you do not need the extra capacity anymore, you can use the trimToSize method.

The trimToSize method tries to recover the storage used by the buffer. If the buffer is larger than what is required to store the current contents of the StringBuffer, this method resizes the internal array for space optimization.

Output

Below given are some of the additional Java StringBuffer examples with detailed explanations on how to use StringBuffer in Java.

Java StringBuffer Examples

References:
Java StringBuffer class Javadoc

Please let me know if you liked the Java StringBuffer tutorial with examples in the comments section below.

About the author

Leave a Reply

Your email address will not be published.