In this java program, we will learn about how to check whether a string is empty or null. Below is a demonstration of the same:
Input String : null Output: True Input String : "ABCD" Output: False Input String : "" Output: True
We consider a string to be empty if it's either null or a string without any length. If a string only consists of whitespace, then we call it blank.
To understand this java program, you should have understanding of the following Java programming concepts:
Java Program to Check if a String is Empty or Null
public class NullEmptyStringCheck {
static String isNullOrEmptyString(String str) {
if (str == null) {
return "Null String";
} else if(str.isEmpty()){
return "Empty String";
} else {
return "Neither Empty nor Null String";
}
}
public static void main(String[] args) {
String str1 = null;
String str2 = "";
String str3 = "ABCD";
System.out.println("str1 is " + isNullOrEmptyString(str1));
System.out.println("str2 is " + isNullOrEmptyString(str2));
System.out.println("str3 is " + isNullOrEmptyString(str3));
}
}
Output
str1 is Null String str2 is Empty String str3 is Neither Empty nor Null String