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

Java 8Object Oriented ProgrammingProgramming

To check if a string is null or empty in Java, use the == operator.

Let’s say we have the following strings.

String myStr1 = "Jack Sparrow";
String myStr2 = "";

Let us check both the strings now whether they are null or empty. Result will be a boolean.

res = (myStr1 == null || myStr1.length() == 0);
res = (myStr2 == null || myStr2.length() == 0);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr1 = "Jack Sparrow";
      String myStr2 = "";
      boolean res;
      res = (myStr1 == null || myStr1.length() == 0);
      System.out.println("String 1 is null or empty? "+res);
      res = (myStr2 == null || myStr2.length() == 0);
      System.out.println("String 2 is null or empty? "+res);
   }
}

Output

String 1 is null or empty? False
String 2 is null or empty? True
raja
Published on 06-Dec-2018 11:43:18
Advertisements