Check if a String is whitespace, empty ("") or null in Java


Let’s say the following is our string.

String myStr = "";

Now, we will check whether the above string is whitespace, empty ("") or null.

if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
   System.out.println("String is not null or not empty or not whitespace");
} else {
   System.out.println("String is null or empty or whitespace");
}

The following is an example that checks for an empty string.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr = "";
      if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
         System.out.println("String is not null or not empty or not whitespace");
      } else {
         System.out.println("String is null or empty or whitespace");
      }
   }
}

Output

String is null or empty or whitespace

Let us see another example that checks for whitespace input.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr = " ";
      if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
         System.out.println("String is not null or not empty or not whitespace");
      } else {
         System.out.println("String is null or empty or whitespace");
      }
   }
}

Output

String is null or empty or whitespace

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements