This post will discuss how to check if a string is empty or null in Java. Note that a string is empty if and only if its length is 0.

1. Using String.isEmpty() method

From Java 7 onward, the recommended approach is to use the String.isEmpty() method to check for an empty string in Java. To avoid NullPointerException if the string is null, a null check should precede the method call.

Download  Run Code

2. Using String.length() method

The isEmpty() method internally calls to the length() method of the String class. In Java 6 and less, since the isEmpty() method is not available, we can directly call the length() method, as shown below:

Download  Run Code

3. Using String.equals() method

One can also use the String.equals() method to do an equality check against an empty string.

Download  Run Code

4. Using Guava Library

Guava’s Strings class has static utility method isNullOrEmpty(String), which returns true if the given string is null or is the empty string.

Download Code

5. Using Apache Commons Lang

Apache Commons Lang library provides StringUtils.isEmpty(String), which checks if a string is an empty string or null. It also provides the StringUtils.isBlank(String) method, which also checks for whitespace.

Download Code

That’s all about determining whether a String is empty or null in Java.