Java String Handling

Check If StringBuilder Is Empty in Java Example (StringBuffer)

Check if StringBuilder is empty in Java example shows how to check StringBuilder is empty in Java (StringBuffer). Example also shows use of length method of the StringBuilder class (StringBuffer).

How to check if StringBuilder is empty in Java (or StringBuffer)?

The Java StringBuilder class provides a length method which returns the number of character it contains.

The length method of the StringBuilder or StringBuffer class returns the length of the sequence of characters it currently has.



As you can see in the example, to check if the StringBuilder is empty, get the length of the StringBuilder object. If the length is 0, it is empty, otherwise not.

Now what do you think will be the output of the below given code?

If your answer is 20, then it is wrong. We have created a new StringBuilder object with 20 as parameter. This constructor creates a StringBuilder object with initial capacity of 20. It is not the length of the StringBuilder object, but it is the number of characters its internal buffer can hold before it needs to be reallocated.

There is difference between StringBuilder length and its capacity. Capacity is the size of the internal buffer while the length is the actual number of characters in the buffer. In above example, we have not put anything in the StringBuilder object so its length will be 0.

Please checkout other StringBuilder examples to learn more about it. Also have a look at String examples to know more and lastly here is how to check if ArrayList is empty in Java.

StringBuilder JavaDoc
StringBuffer JavaDoc

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.