How to check if a string is empty or null in Java

1 Answer

0 votes
public class CheckIfStringIsEmptyOrNull_Java {
    public static String isEmptyOrNull(String str) {
        if (str == null) {
            return "null";
        } else if (str.isEmpty()) {
                    return "empty";
                } else {
                    return "not null or empty";
                  }
    }        
    public static void main(String args[]) {
        String str1 = "";
        String str2 = null;
        String str3 = "  ";
        String str4 = "java";
 
        System.out.println("str1 is: " + isEmptyOrNull(str1));
        System.out.println("str2 is: " + isEmptyOrNull(str2));
        System.out.println("str3 is: " + isEmptyOrNull(str3));
        System.out.println("str4 is: " + isEmptyOrNull(str4));
    }
}

   
    
/*
run:
   
str1 is: empty
str2 is: null
str3 is: not null or empty
str4 is: not null or empty
 
*/

 



answered Jan 15, 2022 by avibootz
edited Nov 5, 2024 by avibootz
...