Checking for Null or Empty in Java.



A string is a collection of characters. In Java, it is represented by the String class, and it accepts NULL values.

Checking for Null or Empty in Java

In this article, we will learn if a string is null or empty in Java. The following are the ways to check if a string is null or empty in Java:

  • Using isEmpty() Method
  • Using length() Method
  • Using isBlank() Method

Using isEmpty() Method

The isEmpty() method of the String class checks if a string is empty. It returns TRUE if the string has no characters, and FALSE otherwise.

Example

Following is an example of checking if a string is null or empty using the isEmpty() method:

public class CheckString {
   public static void main(String[] args) {
      String input = "";

      if (input.isEmpty()) {
         System.out.println("The string is empty.");
      } else {
         System.out.println("The string is not empty.");
      }
   }
}

Following is the output of the above code:

The string is empty.    

Using length() Method

The length() method of the String class returns the number of characters in a string. If the length is 0, then the string is empty.

Example

The following is an example of checking if a string is null or empty using the length() method:

public class CheckStringLength {
   public static void main(String[] args) {
      String input = "Ajj";

      if (input.length() == 0) {
         System.out.println("The string is empty.");
      } else {
         System.out.println("The string is not empty.");
      }
   }
}

Following is the output of the above code:

The string is not empty.

Using isBlank() Method

We can check whether a particular String is empty or not, using the isBlank() method of the StringUtils class. This method accepts an integer as a parameter and returns true if the given string is empty, or false if it is not.

Example

The following is an example of checking if a string is null or empty using the isBlank() method:

import org.apache.commons.lang3.StringUtils;
public class CheckStringBlank {
   public static void main(String[] args) {
      String input = " ";

      if (StringUtils.isBlank(input)) {
         System.out.println("The string is empty or contains only whitespace.");
      } else {
         System.out.println("The string is not empty.");
      }
   }
}

Following is the output of the above code:

The string is empty or contains only whitespace.
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-08-04T18:24:21+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements