Java String is Null or Empty

Java String is null or empty example shows how to check if the String is null or empty in Java. There are a couple of ways using which we can check the string.

How to check if the String is null or empty in Java?

Checking the null string is fairly simple. We need to compare the String reference with null using the == operator. Please see the below example that checks that.

Output

Important Note: We cannot check if the string is null using the equals or equalsIgnoreCase methods. In case the string is indeed null, these methods will throw NullPointerException. Please see the below example.

Output

It throws this exception because, since the string reference is null, calling any methods on the null reference throws the NullPointerException.

Checking for an empty string can be done using several ways. We can use the length method of the string, we can use the isEmpty method, or we can use the equals/equalsIgnoreCase methods.

The String length method returns an int value representing the number of characters it contains. We can compare this with 0 to check if the string is empty.

Output

We can also use the isEmpty method to check the same. This method returns a boolean value, true if the string is empty, false otherwise.

Output

The isEmpty method was introduced in Java 1.6 and internally calls the length method to check. It is recommended to use the isEmpty method instead of the length method to check if the string is empty.

Now to check both, null and empty, we need to combine both of these checks using the OR operator “||” as given below.

Output

Important Note: The order of the null and empty checks is important here. We cannot first check for the empty and then null value because then if the string is null, it will throw NullPointerException.

Lastly, if you are using the Guava library, you can use the isNollOrEmpty method of the Strings class to check. It returns true if the string is null or empty, false otherwise.

Similarly, if you are using the Apache commons library, you can use the isEmpty method of the StringUtils class to check for the empty string.

If you want to learn more about the strings, please visit the Java String 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 *