Skip to content

Java StringBuilder remove last character example (StringBuffer)

This example shows how to remove the last character from the StringBuilder or StringBuffer object using the deleteCharAt and setLength methods. It also shows the best way to delete the last character.

How to remove the last character from the StringBuilder or StringBuffer?

1. Using the deleteCharAt method

We can use the deleteCharAt method to remove the character at any given index from the StringBuilder or StringBuffer object.

This method removes a character located at the specified index. To remove the last character, we need to pass StringBuilder length – 1 as the index to the deleteCharAt method, as shown in the below example.

Output

Before calling the deleteCharAt method always check that the length of the StringBuilder object is greater than 0 to avoid the StringIndexOutOfBoundsException exception.

2. Using the setLength method

We can also use the setLength method of the StringBuilder class to remove the last character from it.

This method sets the length of the character sequence stored in the StringBuilder or StringBuffer object. To remove the last character, we need to pass StringBuilder length – 1 to the setLength method as given below.

Output

What is the best way to remove the last character from StringBuilder or StringBuffer?

Let’s have a look at the source code for both of these methods. Here is the source code of the deleteCharAt method which is directly taken from the OpenJDK 8 AbstractStringBuilder class.

And here is the source code of the setLength method.

By looking at the source code above, we can see that the deleteCharAt method uses the arraycopy method of the System class to remove the specified character from the StringBuilder object. Whereas, the setLength method simply sets the internal buffer count to the specified new length if the current length is greater than or equal to the new length (that is the case when we want to remove a character).

To copy an array is a costly operation as compared to setting the value of an internal variable in terms of performance. Hence, the setLength method should be used to remove the last character over deleteCharAt method due to performance reasons.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.