Horje
Program to check if the String is Empty in Java

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

// Java Program to check if
// the String is empty in Java
 
class GFG {
 
    // Function to check if the String is empty
    public static boolean isStringEmpty(String str)
    {
 
        // check if the string is empty or not
        // using the isEmpty() method
        // and return the result
        if (str.isEmpty())
            return true;
        else
            return false;
    }
 
    // Driver code
    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

// Java Program to check if
// the String is empty in 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



Reffered: https://www.geeksforgeeks.org


DSA

Related
Count number of ways to cover a distance | Set 2 Count number of ways to cover a distance | Set 2
Reduce a number to 1 by performing given operations | Set 2 Reduce a number to 1 by performing given operations | Set 2
First substring whose reverse is a word in the string First substring whose reverse is a word in the string
Program to find the time remaining for the day to complete Program to find the time remaining for the day to complete
Find an integer that is common in the maximum number of given arithmetic progressions Find an integer that is common in the maximum number of given arithmetic progressions

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10