Java String Handling

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. Example also shows the best way to check if the string is empty in Java.

How to check if String is empty in Java?

There are several ways using which you can check if string is empty in Java.

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

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

Output

Well, equals method throws NullPointerException if the string is null. It is always recommended to check for null string before invoking any methods.

Change the below given code to avoid NullPointerException in your code.

Output

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

Output

2) Check if String is empty using length method of String class

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

Output

3) Check if String is empty using isEmpty method of String class (Java 1.6 and later)

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

Output

4) Check if String is empty using Apache Commons library

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

Output

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

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

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.