Program to check if the String is Empty in Java
Last Updated :
28 Jul, 2022
Given a string str, the task is to check if this string is empty or not, in Java. Examples:
Input: str = ""
Output: True
Input: str = "GFG"
Output: False
Approach 1:
if (str.isEmpty())
- Print true if the above condition is true. Else print false.
Below is the implementation of the above approach:
Java
class GFG {
public static boolean isStringEmpty(String str)
{
if (str.isEmpty())
return true ;
else
return false ;
}
public static void main(String[] args)
{
String str1 = "GeeksforGeeks";
String str2 = "";
System.out.println("Is string \"" + str1
+ "\" empty? "
+ isStringEmpty(str1));
System.out.println("Is string \"" + str2
+ "\" empty? "
+ isStringEmpty(str2));
}
}
|
Output:
Is string "GeeksforGeeks" empty? false
Is string "" empty? true
Approach 2: Using length() method
If the length of the string is zero then the string is empty.
Java
class GFG{
public static void main(String[] args)
{
String str1 = "GeeksforGeeks" ;
String str2 = "" ;
boolean res1= false ;
boolean res2= false ;
if (str1.length()== 0 ){
res1= true ;
}
if (str2.length()== 0 ){
res2= true ;
}
System.out.println( "Is string \"" + str1+ "\" empty? " + res1);
System.out.println( "Is string \"" + str2+ "\" empty? " + res2);
}
}
|
Output
Is string "GeeksforGeeks" empty? false
Is string "" empty? true
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...