Java String isEmpty() example

In this guide, you will learn about the String isEmpty() method in Java programming and how to use it with an example.

1. String isEmpty() Method Overview

Definition:

The isEmpty() method in Java's String class is utilized to check if a given string has a length of zero, essentially determining whether the string is empty or not.

Syntax:

str.isEmpty()

Parameters:

- The method takes no parameters.

Key Points:

- Returns true if the string has a length of 0, otherwise false.

- It's a more readable alternative to checking the string length using str.length() == 0.

- Useful in scenarios like form validation, parsing input, etc., to ensure data presence.

2. String isEmpty() Method Example

public class IsEmptyExample {
    public static void main(String[] args) {
        String emptyString = "";
        String nonEmptyString = "Java";
        String whitespaceString = " ";

        // Checking an empty string
        boolean isEmpty1 = emptyString.isEmpty();
        System.out.println("Is the emptyString empty? " + isEmpty1);

        // Checking a non-empty string
        boolean isEmpty2 = nonEmptyString.isEmpty();
        System.out.println("Is the nonEmptyString empty? " + isEmpty2);

        // Checking a whitespace string
        boolean isEmpty3 = whitespaceString.isEmpty();
        System.out.println("Is the whitespaceString empty? " + isEmpty3);
    }
}

Output:

Is the emptyString empty? true
Is the nonEmptyString empty? false
Is the whitespaceString empty? false

Explanation:

In the example:

1. We first check an empty string using the isEmpty() method. As expected, the method returns true for the empty string.

2. Next, we check a non-empty string "Java". Since the string contains characters, the method returns false.

3. Lastly, we evaluate a string containing just a whitespace. It's essential to note that the isEmpty() method considers a string with whitespace as non-empty. Therefore, it returns false.

Related Java String Class method examples

Comments