How to Check If a Double Object Is Null in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a Double object is null in Java. We will explore the difference between primitive double and the Double wrapper class, and how to handle potential NullPointerException errors.

The lab will guide you through checking for null using the equality operator, distinguishing between null and zero values, and utilizing the Optional class for more robust null handling. You will implement and test code examples to solidify your understanding of these concepts.


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/data_types("Data Types") java/BasicSyntaxGroup -.-> java/variables("Variables") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("Wrapper Classes") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/data_types -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} java/variables -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} java/if_else -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} java/classes_objects -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} java/wrapper_classes -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} java/object_methods -.-> lab-559944{{"How to Check If a Double Object Is Null in Java"}} end

Check Double Wrapper for Null

In this step, we will explore how to handle Double wrapper objects in Java, specifically focusing on checking if a Double variable is null. Unlike primitive types like double, wrapper classes like Double can hold a null value, which represents the absence of a value. It's crucial to handle null values correctly to prevent NullPointerException errors in your programs.

Let's create a simple Java program to demonstrate checking for null in a Double object.

  1. Open the HelloJava.java file in the WebIDE editor. If you don't have it open, you can find it in the File Explorer on the left under the ~/project directory.

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

    public class HelloJava {
        public static void main(String[] args) {
            Double price = null; // Declare a Double variable and initialize it to null
    
            if (price == null) {
                System.out.println("Price is not set (it is null).");
            } else {
                System.out.println("Price is set to: " + price);
            }
    
            Double quantity = 10.5; // Declare another Double variable and give it a value
    
            if (quantity == null) {
                System.out.println("Quantity is not set (it is null).");
            } else {
                System.out.println("Quantity is set to: " + quantity);
            }
        }
    }

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

    • Double price = null;: We declare a variable named price of type Double and assign it the value null.
    • if (price == null): This is an if statement that checks if the price variable is equal to null. The == operator is used to compare if the reference to the object is null.
    • System.out.println("Price is not set (it is null).");: This line will be executed if the price is indeed null.
    • Double quantity = 10.5;: We declare another Double variable named quantity and assign it a numerical value.
    • The second if statement checks if quantity is null. Since we assigned it a value, this condition will be false.
  3. Save the HelloJava.java file (Ctrl+S or Cmd+S).

  4. Now, compile the modified program. Open the Terminal at the bottom of the WebIDE and run the following command:

    javac HelloJava.java

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

  5. Finally, run the compiled program:

    java HelloJava

    You should see the following output:

    Price is not set (it is null).
    Quantity is set to: 10.5

    This output confirms that our program correctly identified that price was null and quantity had a value.

Understanding how to check for null is fundamental when working with Java objects, especially wrapper classes. In the next step, we will explore the difference between a null Double and a Double with a value of zero.

Handle Null vs Zero Values

In the previous step, we learned how to check if a Double wrapper object is null. Now, let's explore the difference between a Double being null and a Double having a value of zero (0.0). This distinction is important because null means "no value," while 0.0 is a specific numerical value.

Consider a scenario where you are tracking the discount applied to a product. A null discount might mean that the discount information is not available, while a discount of 0.0 means there is explicitly no discount applied.

Let's modify our HelloJava.java program to demonstrate this difference.

  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) {
            Double discount = null; // Discount information not available
    
            if (discount == null) {
                System.out.println("Discount information is not available (it is null).");
            } else if (discount == 0.0) {
                System.out.println("There is no discount (value is 0.0).");
            } else {
                System.out.println("Discount applied: " + discount);
            }
    
            System.out.println("---"); // Separator for clarity
    
            Double zeroDiscount = 0.0; // Explicitly no discount
    
            if (zeroDiscount == null) {
                System.out.println("Discount information is not available (it is null).");
            } else if (zeroDiscount == 0.0) {
                System.out.println("There is no discount (value is 0.0).");
            } else {
                System.out.println("Discount applied: " + zeroDiscount);
            }
    
            System.out.println("---"); // Separator for clarity
    
            Double appliedDiscount = 5.5; // A specific discount value
    
            if (appliedDiscount == null) {
                System.out.println("Discount information is not available (it is null).");
            } else if (appliedDiscount == 0.0) {
                System.out.println("There is no discount (value is 0.0).");
            } else {
                System.out.println("Discount applied: " + appliedDiscount);
            }
        }
    }

    In this updated code:

    • We introduce three Double variables: discount (initialized to null), zeroDiscount (initialized to 0.0), and appliedDiscount (initialized to 5.5).
    • We use an if-else if-else structure to check the state of each variable:
      • First, we check if the variable is null.
      • If it's not null, we then check if its value is 0.0.
      • Otherwise, we assume a specific discount value is applied.
  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 the following output:

    Discount information is not available (it is null).
    ---
    There is no discount (value is 0.0).
    ---
    Discount applied: 5.5

    This output clearly shows how Java distinguishes between a null Double and a Double with a value of 0.0. Handling these cases correctly is essential for writing robust Java applications.

In the next step, we will explore a more modern approach to handling potential null values using the Optional class, which can make your code safer and more readable.

Test with Optional Class

In modern Java (Java 8 and later), the Optional class is often used to represent a value that may or may not be present. This provides a more explicit and safer way to handle potential null values compared to simply using null references. Using Optional can help prevent NullPointerException errors and make your code more readable.

Let's rewrite our discount example using the Optional<Double> class.

  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) {
            // Representing a discount that might be null
            Optional<Double> optionalDiscount = Optional.empty();
    
            if (optionalDiscount.isPresent()) {
                System.out.println("Discount is present: " + optionalDiscount.get());
            } else {
                System.out.println("Discount is not present (Optional is empty).");
            }
    
            System.out.println("---"); // Separator for clarity
    
            // Representing a discount with a value of 0.0
            Optional<Double> optionalZeroDiscount = Optional.of(0.0);
    
            if (optionalZeroDiscount.isPresent()) {
                System.out.println("Discount is present: " + optionalZeroDiscount.get());
            } else {
                System.out.println("Discount is not present (Optional is empty).");
            }
    
            System.out.println("---"); // Separator for clarity
    
            // Representing a discount with a specific value
            Optional<Double> optionalAppliedDiscount = Optional.of(5.5);
    
            if (optionalAppliedDiscount.isPresent()) {
                System.out.println("Discount is present: " + optionalAppliedDiscount.get());
            } else {
                System.out.println("Discount is not present (Optional is empty).");
            }
    
            System.out.println("---"); // Separator for clarity
    
            // A common way to handle Optional: using orElse
            Double finalDiscount = optionalDiscount.orElse(0.0);
            System.out.println("Using orElse: Final discount is " + finalDiscount);
    
            Double finalZeroDiscount = optionalZeroDiscount.orElse(0.0);
            System.out.println("Using orElse: Final zero discount is " + finalZeroDiscount);
        }
    }

    Let's look at the key changes:

    • import java.util.Optional;: We import the Optional class.
    • Optional<Double> optionalDiscount = Optional.empty();: We create an empty Optional<Double>, representing the absence of a discount value.
    • Optional<Double> optionalZeroDiscount = Optional.of(0.0);: We create an Optional<Double> containing the value 0.0. Optional.of() is used when you are sure the value is not null.
    • Optional<Double> optionalAppliedDiscount = Optional.of(5.5);: We create an Optional<Double> containing the value 5.5.
    • optionalDiscount.isPresent(): This method checks if the Optional contains a value. It's the recommended way to check instead of comparing to null.
    • optionalDiscount.get(): This method retrieves the value from the Optional. Be careful: If the Optional is empty, calling get() will throw a NoSuchElementException. Always check isPresent() before calling get(), or use alternative methods like orElse().
    • optionalDiscount.orElse(0.0): This method returns the value inside the Optional if it's present; otherwise, it returns the default value provided (in this case, 0.0). This is a safe way to get a value and handle the case where the Optional is empty.
  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 the following output:

    Discount is not present (Optional is empty).
    ---
    Discount is present: 0.0
    ---
    Discount is present: 5.5
    ---
    Using orElse: Final discount is 0.0
    Using orElse: Final zero discount is 0.0

    This output demonstrates how Optional helps us explicitly handle cases where a value might be missing. Using Optional can lead to cleaner and more robust code by reducing the risk of NullPointerException.

You have now learned how to check for null in Double wrapper objects, differentiate between null and zero values, and use the Optional class for safer handling of potentially missing values. These are important concepts for writing reliable Java code.

Summary

In this lab, we learned how to check if a Double wrapper object in Java is null. We saw that unlike primitive double, Double can hold a null value. We demonstrated how to use the == null comparison to check for the absence of a value in a Double variable and prevent potential NullPointerException errors. We also explored the difference between a null value and a zero value for a Double object and how to handle both cases appropriately. Finally, we were introduced to the Optional class as a modern Java approach to handle potential null values more explicitly and safely.