Java StringBuilder Tutorial with Examples

Java StringBuilder tutorial with examples will help you understand how to use Java StringBuilder in an easy way. StringBuilder in Java is a mutable sequence of characters. Unlike String, the content of the StringBuilder can be changed after it is created using its methods.

The StringBuilder in Java 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 StringBuilder class.

Difference between StingBuilder and StringBuffer

The StringBuilder class API is similar to that of the StringBuffer, with one difference. The StringBuilder in Java is not synchronized. That means you will have to take care of the synchronization if your code is trying to modify the contents of the StringBuilder using multiple threads.

However, if the code is single threaded, you should prefer to use StringBuilder instead of the StringBuffer. StringBuilder gives better performance in comparison to StringBuffer due to less overhead of the synchronization.

How to create new objects of StringBuilder in Java?

The StringBuilder class in Java provides several constructors to create new objects. The default no argument constructor creates a new empty StringBuilder object having an initial capacity of 16 characters.

The overloaded StringBuilder constructor with a String argument allows us to create a StringBuilder object from the String object as given below.

Output

The StringBuilder class also has an overloaded constructor that accepts the CharSequence argument. You can create a new StringBuilder object from the StringBuffer object using this constructor.

Output

There is also an overloaded constructor that accepts the initial capacity of the StringBuilder object which I will talk about at the end of this tutorial.

How to append content to StringBuilder using the append method?

The StringBuilder class provides several overloaded append methods using which we can append the content of the different data types to the StringBuilder object. The append method has been overloaded to accept boolean, char, character array, CharSequence, double, float, int, long, Object, String, and StringBuffer types.

Output

How to insert content to StringBuilder using the insert method?

The insert method of the StringBuilder class inserts specified data into the StringBuilder content at the specified position. Just like the append method, the insert method is overloaded for boolean, char, character array, int, long, double, float, String, Object, and CharSequence types.

The below given example shows how to insert a String into the StringBuilder object.

Output

If you want to insert substring of String to StringBuilder instead of whole string, you can use the overloaded insert method as given below.

Output

How to insert at front of the StringBuilder (beginning of the StringBuilder)?

Specify the index as 0 to insert the content at the front of the StringBuilder or at the beginning of the StringBuilder object.

Output

How to get the character at the specified index of StringBuilder using the charAt method?

The charAt method of the StringBuilder class returns a character in the StringBuilder at the specified index.

Output

The specified index must be greater than or equal to zero and less than the StringBuilder length. The charAt method throws IndexOutOfBoundsException if the specified index is negative or it is greater than or equal to the length of the StringBuilder object.

How to get the length of the StringBuilder (size of StringBuilder) using the length method?

The StringBuilder length method returns the number of characters contained in the StringBuilder object. It returns zero if the StringBuilder is empty.

Output

How to delete characters from StringBuilder using the delete and deleteCharAt methods?

The deleteCharAt method deletes a character in the StringBuilder at the specified index.

Output

The deleteCharAt method throws StringIndexOutOfBoundsException if the specified index is negative or it is greater than or equal to the length of the StringBuilder object.

How to delete substring from StringBuilder?

The delete method of the StringBuilder class deletes substring from this StringBuilder object.

The startIndex is inclusive while the endIndex is exclusive. If the startIndex is equal to endIndex, no changes are made to the StringBuilder object.

Output

The delete method throws StringIndexOutOfBoundsException if the start index is less than zero, greater than the length, or greater than the end index.

How to copy characters from StringBuilder to an array using the getChars method?

The StringBuilder getChars method copies characters from StringBuilder object starting and ending at the specified index to the specified character array.

The srcIndexStart is inclusive while the srcIndexEnd is exclusive. The total number of characters to be copied to the array are srcIndexEnd – srcIndexStart. The characters are copied to the array starting from the arrayStartIndex index.

Output

The getChars method throws IndexOutOfBoundsException if the srcIndexStart or srcIndexEnd index is negative, srcIndexStart is greater than the srcIndexEnd index, srcIndexEnd index is greater than the StringBuilder length, or arrayStartIndex + (srcIndexEnd  – srcIndexStart) is greater than the array length.

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

How to search the first occurrence of a substring in StringBuilder?

The StringBuilder indexOf method returns the first occurrence of the specified substring within this StringBuilder. It returns -1 if the StringBuilder does not contain the specified substring.

Output

If you want to search for a substring after the specified index of the StringBuilder, use the overloaded indexOf method and specify the start index as given below.

Output

How to search the last occurrence of a substring in StringBuilder?

The StringBuilder lastIndexOf method returns the index of the last occurrence of the specified substring within the StringBuilder object. If the substring is not found, it returns -1.

Output

If you want to search the last occurrence of the substring from the given index, use the overloaded lastIndexOf method as given below.

Output

How to change the length of the StringBuilder using the setLength method?

The StringBuilder setLength method sets the length of this StringBuilder object. If the new length is greater than the StringBuilder length, the rest of the characters will be filled by a null character (i.e. ‘\u0000’). If the new length is less than the StringBuilder length, the rest of the characters are truncated.

Output

The setLength method throws IndexOutOfBoundsException if the specified new length is negative.

How to check if the StringBuilder is empty?

You can use the length method and compare it with zero to check if the StringBuilder is empty.

Output

Please visit the full example of how to check if StringBuilder is empty example to know more.

How to empty or clear the StringBuilder?

Use the setLength method to empty the StringBuilder content as given below.

Output

There are three options to clear or empty the StringBuilder object. Please visit the full example of how to empty StringBuilder to know what are they and what is the best way to empty the StringBuilder object.

How to replace a character at the specified index of StringBuilder using the setCharAt method?

The StringBuilder setCharAt method replaces the current character at the given index with the specified new character.

Output

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

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

The StringBuilder replace method replaces substring within this StringBuilder object with the given String at the specified start and end index.

The startIndex is inclusive, while the endIndex is exclusive.

Output

If the specified endIndex index is greater than the length of the StringBuilder, the replacement will be done till the end of the StringBuilder content. The replace method throws StringIndexOutOfBoundsException if the start index is negative, greater than the StringBuilder length, or greater than the end index.

How to reverse the StringBuilder using the reverse method?

The StringBuilder reverse method replaces StringBuilder’s content with the reverse of the content.

Output

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

The StringBuilder substring method returns a substring from the StringBuilder starting at the specified index till the end of the content.

Here, the startIndex is inclusive.

Output

This method throws StringIndexOutOfBoundsException is the start index is negative or greater than the StringBuilder length.

Use an overloaded substring method if you want to take substring starting and ending at the specified index.

Output

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

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

The StringBuilder subSequence method returns a new String containing the substring from this StringBuilder object starting and ending at the specified index.

This method behaves in the same way as the substring method, the only difference is this method returns CharSequence while the substring method returns a String object. This method is provided so that the StringBuilder class can implement the CharSequence interface.

How to convert StringBuilder to String using the toString method?

The StringBuilder toString method returns a string representation of this StringBuilder object. A new String object is created containing the content of this StringBuilder object and returned.

Output

How to copy one StringBuilder object to another StringBuilder object?

You can use the StringBuilder constructor to copy one StringBuilder to another as given below.

Output

You can also use the same constructor to copy StringBuffer to StringBuilder object.

Output

The StringBuilder append method can be used as well to copy as given below.

Output

What is StringBuilder capacity and how to manage it efficiently?

The StringBuilder class internally manages an array to store its contents. The length of this array is called StringBuilder capacity. The capacity of the StringBuilder is automatically increased as we add more content to it. The StringBuilder class does this by allocating a new internal array with the required length. The default capacity of the StringBuilder object is 16.

In normal scenarios, we do not need to worry about the capacity of the StringBuilder object. However, if you are planning to add large amount of data to StringBuilder, it needs to allocate a new internal array very frequently to fit the content which is a very costly operation in terms of performance.

In such cases, you can create a StringBuilder object with the desired approximate capacity to avoid frequent new array allocation. For example, if you want to store approximately 10000 characters in the StringBuilder, you can allocate that much space upfront using the below given constructor.

You can get the current capacity of StringBuilder object using the capacity method. If you want to change the capacity of the existing StringBuilder object, use the ensureCapacity method.

This method ensures that the StringBuilder capacity is at least equal to the specified minimum capacity. If the specified minimum capacity is greater than the current capacity, this method allocates a new internal array with a new capacity which is larger of the specified minimum capacity or (old capacity * 2) + 2.

Output

It is a good practice to allocate the approximate capacity to the StringBuilder object before adding large data to it. The performance improvement is noticeable if the capacity is allocated as per the size of the data that needs to be inserted into the StringBuilder object.

Once increased, the StringBuilder capacity does not decrease automatically if you store less content later on. So for example, if you have allocated 10000 capacity to StringBuilder object but later on you do not need this much capacity, you need to decrease it using the trimToSize method. This method tries to allocate a new internal array of the smaller size required to fit the StringBuilder content.

Output

Below given are some of the Java StringBuilder examples which show how to use StringBuilder in Java.

Java StringBuilder Examples

References:
Java StringBuilder class Javadoc

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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