There are many ways to check if String is null or empty in Java. We will explore the following:
- Basic code check
- Using the isEmpty() method from String class
- Using the isEmpty() method from StringUtils class
Check if String is null or empty with a basic code check
We can write the basic check like in the following example:
public class Test { public static void main(String[] args) { String str = "Not null or empty String"; if (str == null || str.length() == 0) { System.out.println("str is null or empty!"); } else { System.out.println("str is not null or empty!"); } String str1 = null; if (str1 == null || str1.length() == 0) { System.out.println("str1 is null or empty!"); } else { System.out.println("str1 is not null or empty!"); } String str2 = ""; // empty string if (str2 == null || str2.length() == 0) { System.out.println("str2 is null or empty!"); } else { System.out.println("str2 is not null or empty!"); } } }
Using the isEmpty() method from String class
We have the isEmpty() method from String class that we can use to check if String is empty, but we still need to perform the null check first, to avoid NullPointerException if we call the method on a null String.
For a complete tutorial on how to handle exceptions in Java, you can check out Exception Handling in Java.
public class Test { public static void main(String[] args) { String str = ""; if (str == null || str.isEmpty()) { System.out.println("String is null or empty!"); } else { System.out.println("String is not null or empty!"); } } }
Using the isEmpty() method from StringUtils class
We have very useful isEmpty() method from StringUtils class that belongs to the Apache Commons library. This method checks for empty String and handles null also.
Note: you need to add the dependency to be able to use this class in your project.
Learn how to do this by following our tutorial on Create Java Project with Maven.
public class Test { public static void main(String[] args) { System.out.println(StringUtils.isEmpty(null)); System.out.println(StringUtils.isEmpty("")); } }