Skip to content

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). This example also shows the use of the 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 that returns the number of characters it contains.

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

Example

Output

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 a parameter. This constructor creates a StringBuilder object with an 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 a larger buffer needs to be reallocated.

There is a 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 the above example, we have not put anything in the StringBuilder object so its length will be 0.

Have a look at the String tutorial with examples to know more and lastly here is how to check if ArrayList is empty in Java.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

References:
StringBuilder JavaDoc
StringBuffer JavaDoc

About the author

Leave a Reply

Your email address will not be published.