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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 17-Dec-2018 06:14:54
Advertisements