How to Check If a String Is Null in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn essential techniques for handling null strings in Java. We will begin by exploring the fundamental method of checking for null using the equality operator (==), understanding why this is crucial to prevent NullPointerException.

Building upon this, you will learn how to combine null checks with checks for empty strings to handle various string states effectively. Finally, we will introduce the Optional class as a modern and safer approach to managing potentially null values, demonstrating how it can improve code readability and prevent common errors.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/variables("Variables") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/StringManipulationGroup -.-> java/strings("Strings") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/operators -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/variables -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/if_else -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/strings -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/classes_objects -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/object_methods -.-> lab-559988{{"How to Check If a String Is Null in Java"}} java/string_methods -.-> lab-559988{{"How to Check If a String Is Null in Java"}} end

Test for Null Using Equality Operator

In this step, we will learn how to check if a string variable in Java is null using the equality operator (==). Understanding how to handle null is crucial in Java programming to prevent errors.

In Java, a variable of a reference type (like String) can hold a special value called null. This means the variable doesn't refer to any object in memory. Trying to use a null variable as if it were a valid object will result in a NullPointerException, which is a common and frustrating error for beginners.

The simplest way to check if a string is null is by using the equality operator (==).

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

  1. Open the WebIDE and make sure you are in the ~/project directory. You can confirm this by looking at the terminal prompt or by typing pwd and pressing Enter.

  2. Create a new Java file named NullCheck.java in the ~/project directory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typing NullCheck.java.

  3. Open the NullCheck.java file in the editor and paste the following code:

    public class NullCheck {
    
        public static void main(String[] args) {
    
            String myString1 = "Hello";
            String myString2 = null;
            String myString3 = ""; // This is an empty string, not null
    
            System.out.println("Checking myString1:");
            if (myString1 == null) {
                System.out.println("myString1 is null");
            } else {
                System.out.println("myString1 is not null");
            }
    
            System.out.println("\nChecking myString2:");
            if (myString2 == null) {
                System.out.println("myString2 is null");
            } else {
                System.out.println("myString2 is not null");
            }
    
            System.out.println("\nChecking myString3:");
            if (myString3 == null) {
                System.out.println("myString3 is null");
            } else {
                System.out.println("myString3 is not null");
            }
        }
    }

    In this code:

    • We declare three String variables: myString1 is assigned a regular string, myString2 is explicitly assigned null, and myString3 is assigned an empty string ("").
    • We use an if statement with the equality operator (==) to check if each string is null.
    • We print a message indicating whether the string is null or not.
  4. Save the NullCheck.java file (Ctrl+S or Cmd+S).

  5. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  6. Compile the Java program using the javac command:

    javac NullCheck.java

    If there are no errors, this command will create a NullCheck.class file in the same directory.

  7. Run the compiled Java program using the java command:

    java NullCheck

    You should see output similar to this:

    Checking myString1:
    myString1 is not null
    
    Checking myString2:
    myString2 is null
    
    Checking myString3:
    myString3 is not null

This output confirms that myString1 and myString3 are not null, while myString2 is null. It's important to note the difference between a null string and an empty string (""). An empty string is a valid String object with zero characters, while a null string variable doesn't point to any object.

Using == null is the standard and correct way to check if a reference variable is null in Java.

Combine Null and Empty Checks

In the previous step, we learned how to check if a string is null. However, in many real-world scenarios, you might also need to check if a string is empty (has zero characters) or contains only whitespace. A string that is null, empty, or contains only whitespace is often considered "blank" or "effectively empty".

Checking for both null and empty strings is a common requirement. You can combine these checks using the logical OR operator (||).

Let's modify our previous program to include checks for both null and empty strings.

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

  2. Modify the main method to include an empty string and combine the checks. Replace the existing main method with the following code:

    public class NullCheck {
    
        public static void main(String[] args) {
    
            String myString1 = "Hello";
            String myString2 = null;
            String myString3 = ""; // This is an empty string
            String myString4 = "   "; // This string contains only whitespace
    
            System.out.println("Checking myString1:");
            if (myString1 == null || myString1.isEmpty()) {
                System.out.println("myString1 is null or empty");
            } else {
                System.out.println("myString1 is not null and not empty");
            }
    
            System.out.println("\nChecking myString2:");
            if (myString2 == null || myString2.isEmpty()) {
                System.out.println("myString2 is null or empty");
            } else {
                System.out.println("myString2 is not null and not empty");
            }
    
            System.out.println("\nChecking myString3:");
            if (myString3 == null || myString3.isEmpty()) {
                System.out.println("myString3 is null or empty");
            } else {
                System.out.println("myString3 is not null and not empty");
            }
    
            System.out.println("\nChecking myString4:");
            // Note: isEmpty() does not check for whitespace
            if (myString4 == null || myString4.isEmpty()) {
                System.out.println("myString4 is null or empty");
            } else {
                System.out.println("myString4 is not null and not empty");
            }
        }
    }

    In this updated code:

    • We added myString4 which contains only whitespace.
    • We use the condition myString == null || myString.isEmpty() to check if a string is either null or empty. The isEmpty() method is a built-in String method that returns true if the string has a length of 0.
    • Important: The isEmpty() method can only be called on a non-null string. If you try to call isEmpty() on a null string, you will get a NullPointerException. Therefore, it is crucial to check for null first using myString == null before calling myString.isEmpty(). The logical OR operator (||) is "short-circuiting", meaning if the first condition (myString == null) is true, the second condition (myString.isEmpty()) is not evaluated, preventing the NullPointerException.
  3. Save the NullCheck.java file.

  4. Compile the modified program in the Terminal:

    javac NullCheck.java
  5. Run the compiled program:

    java NullCheck

    You should see output similar to this:

    Checking myString1:
    myString1 is not null and not empty
    
    Checking myString2:
    myString2 is null or empty
    
    Checking myString3:
    myString3 is null or empty
    
    Checking myString4:
    myString4 is not null and not empty

Notice that myString4 (which contains only whitespace) is considered "not null and not empty" by this check. If you need to also consider strings with only whitespace as "blank", you can use the isBlank() method (available since Java 11).

Let's quickly update the code to use isBlank() for myString4:

  1. Modify the check for myString4 in NullCheck.java:

    // ... (previous code) ...
    
            System.out.println("\nChecking myString4 with isBlank():");
            if (myString4 == null || myString4.isBlank()) {
                System.out.println("myString4 is null or blank");
            } else {
                System.out.println("myString4 is not null and not blank");
            }
        }
    }
  2. Save the file, compile, and run again:

    javac NullCheck.java
    java NullCheck

    The output for myString4 should now be:

    Checking myString4 with isBlank():
    myString4 is null or blank

This demonstrates how to combine checks for null and empty/blank strings, which is a very common pattern in Java programming.

Use Optional to Handle Null Strings Safely

In the previous steps, we used the equality operator (==) and the isEmpty() or isBlank() methods to check for null and empty/blank strings. While these methods are effective, Java 8 introduced the Optional class as a way to handle potentially null values in a more explicit and functional way. Using Optional can help make your code more readable and less prone to NullPointerExceptions.

Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. If no value is present, the object is considered empty and isPresent() will return false. Calling get() on an empty Optional will throw a NoSuchElementException.

Let's explore how to use Optional with strings.

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

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

    import java.util.Optional;
    
    public class NullCheck {
    
        public static void main(String[] args) {
    
            String myString1 = "Hello";
            String myString2 = null;
            String myString3 = "";
            String myString4 = "   ";
    
            // Creating Optional objects from strings
            Optional<String> optionalString1 = Optional.ofNullable(myString1);
            Optional<String> optionalString2 = Optional.ofNullable(myString2);
            Optional<String> optionalString3 = Optional.ofNullable(myString3);
            Optional<String> optionalString4 = Optional.ofNullable(myString4);
    
            System.out.println("Checking optionalString1:");
            if (optionalString1.isPresent()) {
                System.out.println("optionalString1 has a value: " + optionalString1.get());
            } else {
                System.out.println("optionalString1 is empty (contains null)");
            }
    
            System.out.println("\nChecking optionalString2:");
            if (optionalString2.isPresent()) {
                System.out.println("optionalString2 has a value: " + optionalString2.get());
            } else {
                System.out.println("optionalString2 is empty (contains null)");
            }
    
            System.out.println("\nChecking optionalString3:");
            // Optional.ofNullable("") creates an Optional containing an empty string
            if (optionalString3.isPresent()) {
                System.out.println("optionalString3 has a value: " + optionalString3.get());
            } else {
                System.out.println("optionalString3 is empty (contains null)");
            }
    
            System.out.println("\nChecking optionalString4:");
             if (optionalString4.isPresent()) {
                System.out.println("optionalString4 has a value: " + optionalString4.get());
            } else {
                System.out.println("optionalString4 is empty (contains null)");
            }
    
            // Using Optional methods for safer handling
            System.out.println("\nUsing Optional methods:");
    
            // orElse: provides a default value if the Optional is empty
            String value1 = optionalString1.orElse("Default Value");
            String value2 = optionalString2.orElse("Default Value");
            System.out.println("Value from optionalString1 (orElse): " + value1);
            System.out.println("Value from optionalString2 (orElse): " + value2);
    
            // ifPresent: performs an action if a value is present
            System.out.print("If optionalString1 is present: ");
            optionalString1.ifPresent(s -> System.out.println("Value is " + s));
    
            System.out.print("If optionalString2 is present: ");
            optionalString2.ifPresent(s -> System.out.println("Value is " + s));
    
            // filter: filters the value if present
            System.out.print("Filtered optionalString1 (length > 3): ");
            optionalString1.filter(s -> s.length() > 3).ifPresent(s -> System.out.println("Value is " + s));
    
            System.out.print("Filtered optionalString3 (length > 3): ");
            optionalString3.filter(s -> s.length() > 3).ifPresent(s -> System.out.println("Value is " + s));
        }
    }

    In this code:

    • We import the Optional class.
    • We use Optional.ofNullable(string) to create an Optional<String> from a regular String. This method is safe to use even if the input string is null. If the input is null, it returns an empty Optional; otherwise, it returns an Optional containing the string.
    • We use optionalString.isPresent() to check if the Optional contains a value.
    • We use optionalString.get() to retrieve the value if it is present. Be careful: calling get() on an empty Optional will throw an exception, so always check isPresent() first or use other safer methods.
    • We demonstrate orElse(defaultValue) which returns the contained value if present, otherwise returns the specified default value.
    • We demonstrate ifPresent(consumer) which executes the given consumer (a function that takes one argument and returns no result) if a value is present.
    • We demonstrate filter(predicate) which returns an Optional containing the value if it is present and matches the given predicate (a function that returns a boolean), otherwise returns an empty Optional.
  3. Save the NullCheck.java file.

  4. Compile the program in the Terminal:

    javac NullCheck.java
  5. Run the program:

    java NullCheck

    You should see output similar to this:

    Checking optionalString1:
    optionalString1 has a value: Hello
    
    Checking optionalString2:
    optionalString2 is empty (contains null)
    
    Checking optionalString3:
    optionalString3 has a value:
    
    Checking optionalString4:
    optionalString4 has a value:
    
    Using Optional methods:
    Value from optionalString1 (orElse): Hello
    Value from optionalString2 (orElse): Default Value
    If optionalString1 is present: Value is Hello
    If optionalString2 is present:
    Filtered optionalString1 (length > 3): Value is Hello
    Filtered optionalString3 (length > 3):

Using Optional can make your code more expressive about whether a value might be absent and provides useful methods for handling the presence or absence of a value without explicit null checks everywhere. While Optional is a powerful tool, it's not a replacement for all null checks, but it's particularly useful when dealing with return values that might be null.

Summary

In this lab, we learned how to check if a string in Java is null. We started by using the equality operator (==) to directly compare a string variable with null, understanding that null signifies the absence of an object reference and that failing to check for null can lead to NullPointerException.

We then explored how to combine the null check with a check for an empty string, recognizing that an empty string ("") is a valid object, unlike null. Finally, we learned how to use the Optional class, introduced in Java 8, as a more modern and safer way to handle potentially null values, promoting more robust and readable code by explicitly indicating the possibility of a missing value.