How to Check If an Integer Object Is Null in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to safely handle Integer wrapper objects in Java, specifically focusing on checking if they are null. Unlike primitive int, Integer is an object that can hold a null reference, and failing to check for null can lead to common NullPointerException errors.

Through practical examples, you will explore the basic == null check, combine null checks with value comparisons, and finally, learn how to leverage the Optional class for more robust and expressive null handling in your Java code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) 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/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("Wrapper Classes") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/operators -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/variables -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/if_else -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/classes_objects -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/exceptions -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/wrapper_classes -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} java/object_methods -.-> lab-560008{{"How to Check If an Integer Object Is Null in Java"}} end

Test Integer Wrapper for Null

In this step, we will explore how to handle Integer wrapper objects in Java, specifically focusing on checking if they are null. Unlike primitive types like int, Integer is a class, which means an Integer variable can hold a reference to an object, or it can be null if it doesn't refer to any object. Handling null values is crucial in Java to prevent NullPointerException errors, which are very common and can crash your program.

Let's create a simple Java program to demonstrate checking for null with an Integer.

  1. Open the HelloJava.java file in the WebIDE editor. If you completed the previous lab, this file should already exist in the ~/project directory.

  2. Replace the existing code in HelloJava.java with the following:

    public class HelloJava {
        public static void main(String[] args) {
            Integer myInteger = null; // Declaring an Integer and setting it to null
    
            // Check if myInteger is null
            if (myInteger == null) {
                System.out.println("myInteger is null.");
            } else {
                System.out.println("myInteger is not null. Its value is: " + myInteger);
            }
    
            // Let's try with a non-null Integer
            Integer anotherInteger = 10; // Declaring and initializing with a value
    
            // Check if anotherInteger is null
            if (anotherInteger == null) {
                System.out.println("anotherInteger is null.");
            } else {
                System.out.println("anotherInteger is not null. Its value is: " + anotherInteger);
            }
        }
    }

    In this code:

    • We declare an Integer variable myInteger and explicitly set it to null.
    • We use an if statement to check if myInteger is equal to null using the == operator. This is the standard way to check if an object reference is null in Java.
    • We then declare another Integer variable anotherInteger and assign it the value 10. Java automatically converts the primitive int value 10 into an Integer object (this is called autoboxing).
    • We perform the same null check on anotherInteger.
  3. Save the HelloJava.java file (Ctrl+S or Cmd+S).

  4. Now, compile the program using the javac command in the Terminal. Make sure you are in the ~/project directory.

    javac HelloJava.java

    If there are no errors, the compilation will complete silently, and a HelloJava.class file will be created in the ~/project directory.

  5. Run the compiled program using the java command:

    java HelloJava

    You should see output similar to this:

    myInteger is null.
    anotherInteger is not null. Its value is: 10

    This output confirms that our null check worked correctly for both the null Integer and the non-null Integer. Understanding how to check for null is a fundamental skill in Java programming, especially when dealing with wrapper classes and objects that might not always have a value assigned.

Combine Null and Value Checks

In the previous step, we learned how to check if an Integer object is null. Often, you'll need to check if an Integer is not null AND if its value meets a certain condition. Combining these checks is important because trying to access the value of a null Integer will result in a NullPointerException.

Let's modify our program to demonstrate combining a null check with a value check.

  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) {
            Integer score = null; // Example 1: score is null
    
            // Check if score is not null AND its value is greater than 50
            if (score != null && score > 50) {
                System.out.println("Score is not null and is greater than 50.");
            } else {
                System.out.println("Score is null or not greater than 50.");
            }
    
            Integer anotherScore = 75; // Example 2: score is 75
    
            // Check if anotherScore is not null AND its value is greater than 50
            if (anotherScore != null && anotherScore > 50) {
                System.out.println("anotherScore is not null and is greater than 50.");
            } else {
                System.out.println("anotherScore is null or not greater than 50.");
            }
    
            Integer yetAnotherScore = 40; // Example 3: score is 40
    
            // Check if yetAnotherScore is not null AND its value is greater than 50
            if (yetAnotherScore != null && yetAnotherScore > 50) {
                System.out.println("yetAnotherScore is not null and is greater than 50.");
            } else {
                System.out.println("yetAnotherScore is null or not greater than 50.");
            }
        }
    }

    In this updated code:

    • We use the logical AND operator (&&) to combine two conditions: score != null and score > 50.
    • The score != null check is placed first. In Java, the && operator uses short-circuit evaluation. This means if the first condition (score != null) is false, the second condition (score > 50) is not evaluated. This prevents a NullPointerException when score is null, because the code score > 50 would not be executed.
    • We test this logic with three different Integer variables: one that is null, one that is not null and greater than 50, and one that is not null but not greater than 50.
  3. Save the HelloJava.java file.

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Score is null or not greater than 50.
    anotherScore is not null and is greater than 50.
    yetAnotherScore is null or not greater than 50.

    This output demonstrates how the combined check works. The first case correctly identifies that score is null. The second case identifies that anotherScore is not null and is greater than 50. The third case identifies that yetAnotherScore is not greater than 50, even though it's not null. This pattern of checking for null before accessing an object's properties or value is a fundamental safety practice in Java.

Use Optional for Safe Handling

While checking for null using == null and combining checks with && is effective, Java 8 introduced the Optional class as a more idiomatic way to handle values that might be absent (i.e., null). Optional is a container object which may or may not contain a non-null value. Using Optional can help make your code more readable and less prone to NullPointerException errors.

In this step, we will refactor our program to use Optional<Integer> to handle potentially absent integer values.

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

  2. Replace the existing code with the following:

    import java.util.Optional;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Example 1: Optional containing a null value (empty Optional)
            Optional<Integer> optionalScoreNull = Optional.empty();
    
            // Check if the Optional contains a value and if it's greater than 50
            if (optionalScoreNull.isPresent() && optionalScoreNull.get() > 50) {
                 System.out.println("optionalScoreNull is present and greater than 50.");
            } else {
                 System.out.println("optionalScoreNull is empty or not greater than 50.");
            }
    
            // Example 2: Optional containing a non-null value (75)
            Optional<Integer> optionalScorePresent = Optional.of(75);
    
            // Check if the Optional contains a value and if it's greater than 50
            if (optionalScorePresent.isPresent() && optionalScorePresent.get() > 50) {
                 System.out.println("optionalScorePresent is present and greater than 50.");
            } else {
                 System.out.println("optionalScorePresent is empty or not greater than 50.");
            }
    
            // Example 3: Optional containing a non-null value (40)
            Optional<Integer> optionalScoreNotGreater = Optional.of(40);
    
            // Check if the Optional contains a value and if it's greater than 50
            if (optionalScoreNotGreater.isPresent() && optionalScoreNotGreater.get() > 50) {
                 System.out.println("optionalScoreNotGreater is present and greater than 50.");
            } else {
                 System.out.println("optionalScoreNotGreater is empty or not greater than 50.");
            }
    
            // A more functional way using Optional methods
            System.out.println("\nUsing Optional methods:");
    
            optionalScoreNull.ifPresent(value -> System.out.println("Value from optionalScoreNull: " + value));
            optionalScorePresent.ifPresent(value -> System.out.println("Value from optionalScorePresent: " + value));
            optionalScoreNotGreater.ifPresent(value -> System.out.println("Value from optionalScoreNotGreater: " + value));
    
            // Using orElse to provide a default value if Optional is empty
            Integer scoreOrDefault = optionalScoreNull.orElse(0);
            System.out.println("Value from optionalScoreNull with default: " + scoreOrDefault);
    
            // Using filter for conditional checks
            optionalScorePresent.filter(value -> value > 50)
                                .ifPresent(value -> System.out.println("Filtered optionalScorePresent value: " + value));
    
             optionalScoreNotGreater.filter(value -> value > 50)
                                .ifPresent(value -> System.out.println("Filtered optionalScoreNotGreater value: " + value));
        }
    }

    Let's look at the key changes:

    • import java.util.Optional;: We import the Optional class.
    • Optional<Integer> optionalScoreNull = Optional.empty();: We create an empty Optional to represent the absence of a value.
    • Optional<Integer> optionalScorePresent = Optional.of(75);: We create an Optional containing a non-null value using Optional.of(). Note that Optional.of() will throw a NullPointerException if you pass it a null value. If the value might be null, use Optional.ofNullable().
    • optionalScoreNull.isPresent(): This method checks if the Optional contains a value. It's the recommended way to check for presence instead of checking for null.
    • optionalScoreNull.get(): This method retrieves the value from the Optional. Be careful! If the Optional is empty, calling get() will throw a NoSuchElementException. This is why you should always check isPresent() before calling get(), or use other Optional methods that handle the empty case gracefully.
    • optionalScoreNull.ifPresent(value -> ...): This method executes the provided code only if the Optional contains a value. It's a clean way to perform an action on the value if it exists.
    • optionalScoreNull.orElse(0): This method returns the value if it's present, otherwise it returns the specified default value (0 in this case).
    • optionalScorePresent.filter(value -> value > 50): This method returns an Optional containing the value if it's present AND matches the given condition (value > 50), otherwise it returns an empty Optional.
  3. Save the HelloJava.java file.

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    optionalScoreNull is empty or not greater than 50.
    optionalScorePresent is present and greater than 50.
    optionalScoreNotGreater is empty or not greater than 50.
    
    Using Optional methods:
    Value from optionalScorePresent: 75
    Value from optionalScoreNotGreater: 40
    Value from optionalScoreNull with default: 0
    Filtered optionalScorePresent value: 75

    This output shows how Optional can be used to handle the presence or absence of values and perform operations safely. While the if (isPresent() && get() > 50) pattern is similar to the null check, Optional provides many other useful methods (ifPresent, orElse, filter, map, etc.) that can lead to more expressive and safer code when dealing with potentially absent values. Using Optional is a good practice in modern Java development.

Summary

In this lab, we learned how to check if an Integer wrapper object is null in Java. We started by understanding that Integer is a class and can hold a null reference, unlike the primitive int. We demonstrated the basic == null check using a simple Java program, showing how to handle both null and non-null Integer variables to prevent NullPointerException.