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.
1 |
public int length() |
In other words, it returns the character count of the StringBuilder.
StringBuilder length example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class StringBuilderLengthExample { public static void main(String[] args) { StringBuilder sbld = new StringBuilder("Hello"); /* * To get the StringBuilder size, use the length method */ int size = sbld.length(); System.out.println("StringBuilder content: " + sbld); System.out.println("Length is: " + size); /* * The size changes as and when we add more * contents to the StringBuilder or StringBuffer object */ sbld.append("world"); size = sbld.length(); System.out.println("StringBuilder content: " + sbld); System.out.println("Length is: " + size); } } |
Output
1 2 3 4 |
StringBuilder content: Hello Length is: 5 StringBuilder content: Helloworld Length is: 10 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuilder sbld = new StringBuilder(""); if(sbld.length() == 0) System.out.println("StringBuilder is empty"); else System.out.println("StringBuilder is not empty"); /* * Or use a shortcut! */ System.out.println("Is StringBuilder empty? " + (sbld.length() == 0) ); |
Output
1 2 |
StringBuilder is empty Is StringBuilder empty? true |
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.
1 2 3 4 5 |
StringBuilder sbld = new StringBuilder("Hello World"); for(int i = 0 ; i < sbld.length() ; i++){ System.out.println( sbld.charAt(i) ); } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
H e l l o W o r l d |
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.