Java StringBuilder length example (StringBuffer length)

This Java 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 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 Java StringBuffer tutorial and Java StringBuilder tutorial.

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *