You can check whether the string size is zero or not by using the isEmpty() method in Java. This method returns a boolean value. On this page, we have shared some examples of this method.

Java String isEmpty():

Method signature:

The signature for an isEmpty() method is as shown below.

public boolean isEmpty()

Method parameters and return type:

Return type: It returns a boolean value either true or false.

Parameters: It doesn’t take any parameters.

Throws: It throws NullPointerException if the string is null.

Example 1:

In this example, we have initialized two strings. The second string has a length of 0. We will use the isEmpty() method to check that which string is empty.

Source code:

public class Example1 {

    public static void main(String args[]) {
        String str1 = "Not Empty";
        String str2 = "";

        System.out.println(str1.isEmpty());
        System.out.println(str2.isEmpty());
    }
}

Output:

run:
false
true
BUILD SUCCESSFUL (total time: 0 seconds)

Example 2:

Here is another example in which we have initialized two strings and passed them through conditional statements. When the strings will pass through the first if condition, the if body will not be executed. After that, we will make both strings empty, and we will pass them again from another if condition.

Source code:

public class Example2 {

    public static void main(String[] args) {
        String str1 = "First string";
        String str2 = "Second string";

        if (str1.isEmpty() && str2.isEmpty()) {
            System.out.println("Strings are empty");
        }

        str1 = "";
        str2 = "";

        if (str1.isEmpty() && str2.isEmpty()) {
            System.out.println("Strings are empty");
        }
    }
}

Output:

run:
Strings are empty
BUILD SUCCESSFUL (total time: 0 seconds)

Example 3:

Here we are checking that on which index of the array, the string length is 0.

Source code:

public class Example3 {
    
    public static void main(String[] args) {
        
        String array[]= {"Dog","","Cat"};
        
        for(int i=0; i<array.length; i++){
            if(array[i].isEmpty() || array[i].length()==0){
                System.out.println("String is null at index: "+i);
            }
        }
    }
}

Output:

run:
String is null at index: 1
BUILD SUCCESSFUL (total time: 0 seconds)

References:

Happy Learning 🙂

Leave A Comment