Skip to content

Check if String is empty in Java example

Check if string is empty in Java example shows how to check if string is empty in Java using the equal method, the length method, isEmpty method, or using apache commons.

How to check if string is empty in Java?

There are several ways using which you can check the string.

1) Check if a string is empty using the equals method of the String class

You can check using the equals method of the String class as given below.

Output

The equals method throws NullPointerException if the string is null. It is always recommended to check for the null string before calling any methods.

To avoid NullPointerException in your code, use the below given code.

Output

You can also use below given code instead of checking both the conditions (not null and empty).

Output

2) Using the length method of the String class

You can also use length method of String class to check. The length method returns 0 if the string is empty.

Output

3) Using the isEmpty method of the String class (Java 1.6 and later)

If you are using Java 1.6 or later version, you can use isEmpty method of the String class as given below.

Output

4) Using the Apache Commons library

The Apache commons library provides many useful utilities. Use the isEmpty method of the StringUtils class to check as given below.

Output

As you might have observed from the output, the isEmpty method also handles the null very well and returns true.

Alternatively, you can also use the isBlank method of the StringUtils class which also checks if the string contains only white spaces as given below.

Output

Check out the how to check if the StringBuilder or StringBuffer is empty and how to check if the ArrayList is empty examples as well.

This example is a part of the String in Java 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.