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.
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.
Open the
HelloJava.javafile in the WebIDE editor. If you don't have it open, you can find it in the File Explorer on the left under the~/projectdirectory.Replace the existing code in
HelloJava.javawith 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 namedpriceof typeDoubleand assign it the valuenull.if (price == null): This is anifstatement that checks if thepricevariable is equal tonull. The==operator is used to compare if the reference to the object isnull.System.out.println("Price is not set (it is null).");: This line will be executed if thepriceis indeednull.Double quantity = 10.5;: We declare anotherDoublevariable namedquantityand assign it a numerical value.- The second
ifstatement checks ifquantityisnull. Since we assigned it a value, this condition will be false.
Save the
HelloJava.javafile (Ctrl+S or Cmd+S).Now, compile the modified program. Open the Terminal at the bottom of the WebIDE and run the following command:
javac HelloJava.javaIf the compilation is successful, you will not see any output.
Finally, run the compiled program:
java HelloJavaYou should see the following output:
Price is not set (it is null). Quantity is set to: 10.5This output confirms that our program correctly identified that
pricewasnullandquantityhad 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.
Open the
HelloJava.javafile in the WebIDE editor.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
Doublevariables:discount(initialized tonull),zeroDiscount(initialized to0.0), andappliedDiscount(initialized to5.5). - We use an
if-else if-elsestructure 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 is0.0. - Otherwise, we assume a specific discount value is applied.
- First, we check if the variable is
- We introduce three
Save the
HelloJava.javafile.Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou should see the following output:
Discount information is not available (it is null). --- There is no discount (value is 0.0). --- Discount applied: 5.5This output clearly shows how Java distinguishes between a
nullDoubleand aDoublewith a value of0.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.
Open the
HelloJava.javafile in the WebIDE editor.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 theOptionalclass.Optional<Double> optionalDiscount = Optional.empty();: We create an emptyOptional<Double>, representing the absence of a discount value.Optional<Double> optionalZeroDiscount = Optional.of(0.0);: We create anOptional<Double>containing the value0.0.Optional.of()is used when you are sure the value is notnull.Optional<Double> optionalAppliedDiscount = Optional.of(5.5);: We create anOptional<Double>containing the value5.5.optionalDiscount.isPresent(): This method checks if theOptionalcontains a value. It's the recommended way to check instead of comparing tonull.optionalDiscount.get(): This method retrieves the value from theOptional. Be careful: If theOptionalis empty, callingget()will throw aNoSuchElementException. Always checkisPresent()before callingget(), or use alternative methods likeorElse().optionalDiscount.orElse(0.0): This method returns the value inside theOptionalif 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 theOptionalis empty.
Save the
HelloJava.javafile.Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou 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.0This output demonstrates how
Optionalhelps us explicitly handle cases where a value might be missing. UsingOptionalcan lead to cleaner and more robust code by reducing the risk ofNullPointerException.
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.



