Check if a String is Empty or Null in Java

Exercise:

Write a Java Program to check if a string is empty or null.

Click Here to View the Solution!
public class NullOrEmpty {
       public static void main(String[] args) {
        String str1 = null;
        String str2 = " Hello";
 
        if(isNullOrEmpty(str1))
            System.out.println("First string is null or empty.");
        else
            System.out.println("First string is not null or empty.");
 
        if(isNullOrEmpty(str2))
            System.out.println("Second string is null or empty.");
        else
            System.out.println("Second string is not null or empty.");
    }
        public static boolean isNullOrEmpty(String str) {
        if(str != null && !str.isEmpty())
            return false;
        return true;
     }
}
Click Here to View the Output!
First string is null or empty.
Second string is not null or empty.
Click Here to View the Explanation!
  • This program is used to find out whether a string is empty or is null by using if…else statements.
  • Initially two string variables str1 and str2 are initialized as str1 = null and str2 = “ Hello”. Which states that string 1 is a null string and string 2 is an empty string.
  • A user-defined function isNullorEmpty() is created that is used to check whether a string is null or is empty. The null condition is checked by stating a condition (!= null) and the empty condition is checked through the .isEmpty() method.
  • If both the conditions, !=null and .isEmpty() are not true for a string, then the function will return false and print that the string is not null or empty. Else, it will return true and print that the string is null or empty.

%d bloggers like this: