Using the StringBuffer class

Since strings are immutable, you may want to use the StringBuffer class if you’re going to alter the String in the code. The StringBuffer class can be seen as a mutable String object which allocates more memory (or deallocates if told so) when it’s content is altered.
It should be said early that the StringBuffer class i thread-safe which means that it automatically handles synchronization of access to the object by different threads.
If you’re using only one thread in your program you should use the StringBuilder class instead since it’s pretty much identical to the StringBuffer class except that it doesn’t handle synchronization.

A StringBuffer object has an attribute called capacity that determines how many bytes that are allocated in the buffer. You can specify at construction time which capacity it should start out with.
When you later add bytes to the buffer it will automatically increase the capacity of the array.
If you don’t specify any capacity at all it will still allocate 16 bytes by default, so if we had a method like this:

…the output would be:

There are also overloaded constructors of the StringBuffer class that takes a String and a CharSequence object as arguments.

To add text to a StringBuffer object you can either add it to the end of the buffer using the append method, or you can specify at what point you want the text to be inserted by using the insert method.
This method shows how to use them both:

The output of the insertTextExample method above will be:

Now, consider we want to delete text from the StringBuffer. For simplicity we use the same code as above to construct the StringBuffer and then we delete the same text as we just added:

The output of the method above will be:

There are several methods in the StringBuffer class and this example just bring up a few of them, perhaps though the ones mostly used.

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?