How to Check If a String Is Empty in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is empty in Java. We will explore three key techniques: using the length() method to verify string length, utilizing the dedicated isEmpty() method for a direct check, and importantly, handling potential null strings before performing emptiness checks to avoid errors. By the end of this lab, you will have a solid understanding of how to effectively determine the emptiness of strings in your Java programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-559927{{"How to Check If a String Is Empty in Java"}} java/string_methods -.-> lab-559927{{"How to Check If a String Is Empty in Java"}} end

Verify String Length Using length() Method

In this step, we will explore how to determine the length of a string in Java using the built-in length() method. Understanding string length is a fundamental concept when working with text data in any programming language.

In Java, a String is a sequence of characters. The length() method is a simple way to find out how many characters are in a string. It's like counting the letters in a word or the words in a sentence.

Let's create a simple Java program to demonstrate this.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            String greeting = "Hello, Java!";
            int length = greeting.length();
            System.out.println("The string is: " + greeting);
            System.out.println("The length of the string is: " + length);
        }
    }

    Let's look at the new parts of this code:

    • String greeting = "Hello, Java!";: This line declares a variable named greeting and assigns it the string value "Hello, Java!".
    • int length = greeting.length();: This is where we use the length() method. We call length() on the greeting string, and it returns the number of characters in that string. This number is then stored in an integer variable named length.
    • System.out.println("The string is: " + greeting);: This line prints the original string to the console.
    • System.out.println("The length of the string is: " + length);: This line prints the calculated length of the string.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Then, run the following command:

    javac HelloJava.java

    If the compilation is successful, you will not see any output.

  5. Finally, let's run the compiled program:

    java HelloJava

    You should see output similar to this:

    The string is: Hello, Java!
    The length of the string is: 12

    The output shows the original string and its length, which is 12 (including the comma, space, and exclamation mark).

You have successfully used the length() method to find the length of a string in Java! This is a basic but important operation when working with text data.

Check for Empty String with isEmpty() Method

In this step, we will learn how to check if a string is empty in Java using the isEmpty() method. An empty string is a string that has zero characters. It's different from a string that contains spaces or other characters.

The isEmpty() method is a convenient way to check if a string has a length of zero. It returns true if the string is empty and false otherwise.

Let's modify our HelloJava.java program to demonstrate the isEmpty() method.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String str1 = "Hello";
            String str2 = ""; // This is an empty string
            String str3 = " "; // This string contains a space
    
            System.out.println("String 1: \"" + str1 + "\"");
            System.out.println("Is String 1 empty? " + str1.isEmpty());
    
            System.out.println("\nString 2: \"" + str2 + "\"");
            System.out.println("Is String 2 empty? " + str2.isEmpty());
    
            System.out.println("\nString 3: \"" + str3 + "\"");
            System.out.println("Is String 3 empty? " + str3.isEmpty());
        }
    }

    In this code:

    • We declare three strings: str1 with content, str2 which is empty, and str3 which contains a space.
    • We use str1.isEmpty(), str2.isEmpty(), and str3.isEmpty() to check if each string is empty.
    • The System.out.println() statements will print the string and the result of the isEmpty() check (true or false).
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java

    Again, no output means successful compilation.

  5. Run the program:

    java HelloJava

    You should see output similar to this:

    String 1: "Hello"
    Is String 1 empty? false
    
    String 2: ""
    Is String 2 empty? true
    
    String 3: " "
    Is String 3 empty? false

    As you can see, isEmpty() correctly identifies str2 as empty (true) but not str1 or str3 (false). This is because str3 contains a space character, even though it looks like it might be empty.

You have successfully used the isEmpty() method to check if strings are empty. This is useful for validating user input or processing text data where you need to handle cases of missing or empty strings.

Handle Null Strings Before Checking Emptiness

In the previous step, we learned how to use the isEmpty() method to check if a string is empty. However, there's an important concept in Java called null. A null value means that a variable does not refer to any object. If you try to call a method like isEmpty() on a null string, your program will crash with a NullPointerException.

It's crucial to handle null strings before attempting to call any methods on them. The safest way to do this is to check if the string is null first.

Let's modify our program to demonstrate how to handle null strings.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String str1 = "Hello";
            String str2 = "";
            String str3 = null; // This string is null
    
            System.out.println("Checking String 1: \"" + str1 + "\"");
            if (str1 != null && !str1.isEmpty()) {
                System.out.println("String 1 is not null and not empty.");
            } else {
                System.out.println("String 1 is null or empty.");
            }
    
            System.out.println("\nChecking String 2: \"" + str2 + "\"");
            if (str2 != null && !str2.isEmpty()) {
                System.out.println("String 2 is not null and not empty.");
            } else {
                System.out.println("String 2 is null or empty.");
            }
    
            System.out.println("\nChecking String 3: " + str3); // Note: printing null doesn't crash
            if (str3 != null && !str3.isEmpty()) {
                System.out.println("String 3 is not null and not empty.");
            } else {
                System.out.println("String 3 is null or empty.");
            }
        }
    }

    In this code:

    • We introduce a null string str3.
    • Before calling isEmpty(), we first check if the string is null using str != null.
    • We use the logical AND operator (&&) to combine the null check and the isEmpty() check. The !str.isEmpty() part is only evaluated if str != null is true, preventing the NullPointerException.
    • The if statement checks if the string is not null AND not empty.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Checking String 1: "Hello"
    String 1 is not null and not empty.
    
    Checking String 2: ""
    String 2 is null or empty.
    
    Checking String 3: null
    String 3 is null or empty.

    This output shows that our code correctly identifies str1 as not null and not empty, and str2 and str3 as null or empty, without crashing.

By checking for null before calling methods on strings, you make your Java programs more robust and prevent common errors. This is a very important practice in Java programming.

Summary

In this lab, we learned how to check if a string is empty in Java. We started by exploring the length() method to determine the number of characters in a string, which is a fundamental concept for working with text data. We wrote a simple Java program to demonstrate how to use length() and print the string and its length to the console.

We will continue to explore other methods like isEmpty() and learn how to handle null strings to ensure robust emptiness checks in our Java programs.