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.
1 |
public int length() |
The length method of the StringBuilder or StringBuffer class returns the length of the sequence of characters it currently has.
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 |
public class JavaStringBuilderCheckEmptyExample { public static void main(String[] args) { //create new StringBuilder object StringBuilder sb = new StringBuilder("Java StringBuilder Check Empty"); if( sb.length() == 0 ){ System.out.println("StringBuilder is empty"); }else{ System.out.println("StringBuilder is not empty"); } //clear contents sb.setLength(0); if( sb.length() == 0 ){ System.out.println("StringBuilder is empty"); }else{ System.out.println("StringBuilder is not empty"); } } } |
Output
1 2 |
StringBuilder is not empty StringBuilder is empty |
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?
1 2 3 |
//create new StringBuilder object StringBuilder sb = new StringBuilder(20); System.out.println(sb.length()); |
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