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


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

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 07-Nov-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements