Check if a String is empty or null in Java
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.
|
1 2 3 4 5 6 7 8 9 |
class Main { public static void main(String[] args) { String str = ""; System.out.println(str == null || str.isEmpty()); // true } } |
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:
|
1 2 3 4 5 6 7 8 9 |
class Main { public static void main(String[] args) { String str = ""; System.out.println(str == null || str.length() == 0); // true } } |
3. Using String.equals() method
One can also use the String.equals() method to do an equality check against an empty string.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Main { private static String EMPTY = ""; public static void main(String[] args) { String str = ""; System.out.println(str == null || str.equals(EMPTY)); // true System.out.println(str == null || EMPTY.equals(str)); // true } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import com.google.common.base.Strings; class Main { public static void main(String[] args) { System.out.println(Strings.isNullOrEmpty("")); // true System.out.println(Strings.isNullOrEmpty(null)); // true System.out.println(Strings.isNullOrEmpty("Java")); // false } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.StringUtils; class Main { public static void main(String[] args) { System.out.println(StringUtils.isEmpty("")); // true System.out.println(StringUtils.isEmpty(null)); // true System.out.println(StringUtils.isEmpty("Java")); // false System.out.println(StringUtils.isBlank(" ")); // true } } |
That’s all about determining whether a String is empty or null in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)