Java String isEmpty() example

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare