Java program to check if a string is empty or null
Certainly, here's a Java program that checks if a string is empty or null:
refer:ot theitroad.compublic class StringChecker { public static void main(String[] args) { String str1 = ""; String str2 = null; // Check if str1 is empty or null if (str1 == null || str1.isEmpty()) { System.out.println("str1 is either null or empty."); } else { System.out.println("str1 is not null or empty."); } // Check if str2 is empty or null if (str2 == null || str2.isEmpty()) { System.out.println("str2 is either null or empty."); } else { System.out.println("str2 is not null or empty."); } } }
In this program, we first create two string variables: str1
is an empty string, and str2
is a null
reference.
We then check if str1
is empty or null by using the ==
operator to check if it's equal to null
, and calling the isEmpty
method to check if it's an empty string. We do the same for str2
.
The output of this program will be:
str1 is either null or empty. str2 is either null or empty.
This indicates that both str1
and str2
are either null or empty.