Check if String is Null or Empty in Java

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!");
    }

  }
}
Output: str is not null or empty! str1 is null or empty! str2 is null or empty!
 
In this example, we check if a given String is null or empty and then we print the appropriate message. An if-else statement is used to check if the String is null or if its length is equal to 0, which would indicate that it is an empty String. If either of these conditions is true, the code prints “str is null or empty!” If neither of these conditions are true, the code prints “str 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!");
    }

  }
}
Output: String is 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(""));

  }
}
Output: true true
 
That’s it!

Leave a Reply

Your email address will not be published.