Learn about StringBuilder object in Java

We often use the StringBuilder object to build String object whose content is aggregated from a variety of conditions. In this tutorial, I will summarize the knowledge needed to work with the StringBuilder object!

Initialize the StringBuilder object

StringBuilder gives us 4 constructors to initialize a StringBuilder object. That is:

A constructor with no parameters.
For example:

A constructor with a parameter defines the initial capacity of the StringBuilder object.
For example:

A constructor with a parameter as an implementation of CharSequence interface.
A constructor with a parameter as a String object.
For example:



The concept of capacity and the StringBuilder object

In terms of initializing the StringBuilder object, I mentioned the concept of capacity. What is the capacity, I would like to say more about it for your understanding?

The capacity here is the ability to contain a String object with a certain length of our StringBuilder object.

By default, if you initialize a StringBuilder object with a constructor without a parameter, the capacity of this object is 16. With the constructor initialized with a capacity, the object created will have the initial capacity equal to the capacity that we pass on.

In the other two cases, the capacity is equal to the length of the CharSequence object or String, plus with 16.

Although there is a capacity you are assured, when you add String with a length greater than capacity, StringBuilder will automatically increase capacity for us so there will not be any problems here.

Add Comment