StringBuffer Class Java | StringBuilder in Java

This chapter is all about StringBuffer Class Java and its important methods to remember. We will also see what StringBuilder in Java is about and learn how they (all three classes String, StringBuffer and StringBuilder) differ from each other.

As we had learned in the String chapter earlier that it was immutable (cannot change the instance), what if we wish to deal with a mutable string?

That’s where StringBuffer Class Java and StringBuilder Class come into the picture.

Choo choo train meme for stringbuffer class java

StringBuffer Class Java has its very own set of methods, some of them are similar to the ones that we had seen for String Class Java. Without wasting any more time, let’s get to it:

StringBuffer Class Java

As mentioned earlier, a StringBuffer Class Java is mutable so you can change the instance here unlike String Class.  Here’s a quickie that will help you see the difference:

StringBuffer s = new StringBuffer("Lift");    

s.append(" me up.");    

System.out.println(s);

If it was a String class (immutable) trying to print ‘s’ here would have given you “Lift”. But it is a StringBuffer Class Java now which is mutable and hence the change will be done on ‘s’ itself. The output would be, you guessed right:

Lift me up.

Let us move on to see all the crucial methods of StringBuffer Class Java.

Since we have already seen append() method before we will try to see the others now.

StringBuffer insert() method

The insert() method of StringBuffer Class Java can be used to insert a particular string at any given position. You can have two or four parameters here, based on your requirement.

In case of a two-parameter method, the first one is generally the offset, the second one whatever you wish to put in. Let’s see an example:

StringBuffer s = new StringBuffer("Late Goodbye");

s.insert(5, "me up ");

System.out.println(s);

The result would be:

Late me up Goodbye

StringBuffer replace() Method

The replace() method of StringBuffer Class Java does the same thing what its moniker suggests it should do.  However, unlike String Class’s replace() method StringBuffer class Java’s replace() has three parameters.

The first two being startIndex and endIndex that are inclusive and exclusive respectively. Here’s the example:

StringBuffer s = new StringBuffer("Late Goodbye");   

s.replace(5, 10, "Bad e");    

System.out.println(s);

Checking the result out:

Late Bad eye

StringBuffer delete() Method

Delete() method is pretty self-explanatory. If you need to chop something down from your string, you could make use of StringBuffer class’s delete() method.

Here you need to only provide the startIndex and endIndex, the rest of the remaining string will be provided as result. Let’s remove the second word from our equation:

StringBuffer s = new StringBuffer("Late Goodbye");    

System.out.println(s.delete(5, 12));

Check out the result you will get:

late

StringBuffer reverse() Method

The reverse() method too is easy to get. Yes, you guessed right. You can reverse a string. Isn’t that cool?

Let’s subject our string to that:

StringBuffer s = new StringBuffer("Late Goodbye");    

System.out.println(s.reverse());

The above would give the following result:

eybdooG etaL

StringBuffer capacity() Method

There’s a method called capacity() of the StringBuffer Class Java that is useful in returning the capacity of the buffer. By default the capacity of the buffer is 16. However, if you keep adding characters, it will increase its capacity.

So the following code:

StringBuffer s = new StringBuffer();

System.out.println(s.capacity());

will give you:

16

When you try to append your string with something that crosses the capacity:

s.append("crazy is he who crazy is");

The result for the above would become:

34

How does it calculate, you ask? Well, the capacity is increased by (oldcapacity*2) + 2. Hence the result was calculated like, 16*2 + 2 = 34

If you wish to provide your string a capacity by default you could do so via your constructor as well. There is a StringBuffer constructor variant that allows you to enter the capacity in integer format. The syntax is:

StringBuffer(int capacity)

So let’s put it in one of our codes and check if the capacity turns out to be the one we expect:

StringBuffer s = new StringBuffer(78);

System.out.println(s.capacity());

If you run the above program you will get:

78

StringBuffer ensureCapacity() Method

You could choose to ensure that your capacity is at least equal to a specified minimum via the ensureCapacity() method.

Remember if you enter a negative number in the capacity field, it will do nothing.

Suppose you have a buffer with 16 capacity. If you want to ensure it is 18 or 19 at least, you could do that using ensureCapacity() method. If your capacity is greater than current capacity, it will increase the capacity using the earlier formula of (oldcapacity*2) + 2.

Here’s an example to depict that:

StringBuffer s = new StringBuffer(16);    

s.ensureCapacity(18);    

System.out.println(s.capacity());

If you run the above program you will get:

34

The capacity has been increased as per the formula.

trimToSize() Method

But in the example above you could see that it created an unnecessary buffer of 14 characters more. We don’t want that, do we? If we are too uptight about buffer space issues, we could choose to just use what we want. The method trimToSize() will remove that extra buffer space.

Here’s an example depicting how to get rid of that extra space.

StringBuffer s = new StringBuffer("Where are you now?");   

s.ensureCapacity(18);    

System.out.println(s.capacity());    

s.trimToSize();    

System.out.println(s.capacity());

If you try to run the above program you will get:

34
18

As you can see the extra space has been chopped off. Our new capacity has become 18 which is the size our string has taken.

StringBuilder in Java

The StringBuilder in Java Class is exactly the same as StringBuffer. The only difference being StringBuffer is synchronized while StringBuilder in Java in unsynchronized. Forgotten the concept of synchronization already, nothing wrong with going back to learn what synchronization is all about.

I am not going to depict examples for StringBuilder because the only change you need to make in the aforementioned examples is:

Make StringBuffer to StringBuilder

And you are done.

The results are going to be the same.

NOTE: StringBuilder in Java is considered to be more efficient than StringBuffer.

The Final Call

People make use of StringBuffer or StringBuilder because they are faster than String in a lot of ways. If you are performing an operation with String say concat() it takes a lot of time, but the same can be achieved within milliseconds via StringBuffer or StringBuilder.

Hope this was another useful session where you learned about what StringBuffer Class is and how similar StringBuilder in Java is to it.

Time to return to my coffin to sleep.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

2 Responses

  1. Worth reading and very good blog!
    I have been looking for the difference between string builder and string buffer, you have differentiated here very well and now i am very much cleared with these concepts. Its important for the java beginners to know about these two.
    Thanks a lot for sharing!

Leave a Reply