Using the StringBuilder class

Since strings are immutable, you may want to use the StringBuilder class if you’re going to alter the String in the code. The StringBuilder class can be seen as a mutable String object which allocates more memory (or deallocates if told so by using the trimToSize() method) when it’s content is altered.
It should be said early that the StringBuilder class is not thread-safe which means that it doesn’t automatically handle synchronization of access to the object by different threads as opposed to the StringBuffer class.
If this object needs to be altered by concurrent threads you must either provide you own code for synchronization or simply use the StringBuffer class instead and have the synchronization implemented automatically.

A StringBuilder 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 StringBuilder class that takes a String and a CharSequence object as arguments.

To add text to a StringBuilder 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 StringBuilder. For simplicity we use the same code as above to construct the StringBuilder 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 StringBuilder 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

Please type any questions here.