Skip to content

Java StringBuilder length example (StringBuffer length)

StringBuilder length example shows how to get the StringBuilder object’s length or size using the length method. Since the StringBuilder class is a drop-in replacement for the StringBuffer class, the example works for StringBuffer too.

How to get the StringBuilder length using the length method?

The length method of the StringBuilder or StringBuffer class returns the number of characters stored in the StringBuilder or StringBuffer object.

In other words, it returns the character count of the StringBuilder.

StringBuilder length example

Output

When we first create an empty StringBuilder, the length method returns 0 as there are no characters in it.

How to check if StringBuilder is empty using the length method?

The length method returns 0 if there are no characters in the StringBuilder or StringBuffer object. We can compare the return value of the length method with 0 to check if the StringBuilder is empty or not.

Output

How to iterate StringBuilder contents using the length method?

We can also iterate over the characters of the StringBuilder or StringBuffer object using for loop as given below.

Output

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

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.