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.
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.
Open the
HelloJava.javafile in the WebIDE editor. If you completed the previous lab, this file should already exist in the~/projectdirectory.Replace the existing code in
HelloJava.javawith 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
IntegervariablemyIntegerand explicitly set it tonull. - We use an
ifstatement to check ifmyIntegeris equal tonullusing the==operator. This is the standard way to check if an object reference isnullin Java. - We then declare another
IntegervariableanotherIntegerand assign it the value10. Java automatically converts the primitiveintvalue10into anIntegerobject (this is called autoboxing). - We perform the same
nullcheck onanotherInteger.
- We declare an
Save the
HelloJava.javafile (Ctrl+S or Cmd+S).Now, compile the program using the
javaccommand in the Terminal. Make sure you are in the~/projectdirectory.javac HelloJava.javaIf there are no errors, the compilation will complete silently, and a
HelloJava.classfile will be created in the~/projectdirectory.Run the compiled program using the
javacommand:java HelloJavaYou should see output similar to this:
myInteger is null. anotherInteger is not null. Its value is: 10This output confirms that our
nullcheck worked correctly for both thenullIntegerand the non-nullInteger. Understanding how to check fornullis 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.
Open the
HelloJava.javafile in the WebIDE editor.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 != nullandscore > 50. - The
score != nullcheck 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 aNullPointerExceptionwhenscoreisnull, because the codescore > 50would not be executed. - We test this logic with three different
Integervariables: one that isnull, one that is notnulland greater than 50, and one that is notnullbut not greater than 50.
- We use the logical AND operator (
Save the
HelloJava.javafile.Compile the modified program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou 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
scoreisnull. The second case identifies thatanotherScoreis notnulland is greater than 50. The third case identifies thatyetAnotherScoreis not greater than 50, even though it's notnull. This pattern of checking fornullbefore 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.
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) { // 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 theOptionalclass.Optional<Integer> optionalScoreNull = Optional.empty();: We create an emptyOptionalto represent the absence of a value.Optional<Integer> optionalScorePresent = Optional.of(75);: We create anOptionalcontaining a non-null value usingOptional.of(). Note thatOptional.of()will throw aNullPointerExceptionif you pass it anullvalue. If the value might benull, useOptional.ofNullable().optionalScoreNull.isPresent(): This method checks if theOptionalcontains a value. It's the recommended way to check for presence instead of checking fornull.optionalScoreNull.get(): This method retrieves the value from theOptional. Be careful! If theOptionalis empty, callingget()will throw aNoSuchElementException. This is why you should always checkisPresent()before callingget(), or use otherOptionalmethods that handle the empty case gracefully.optionalScoreNull.ifPresent(value -> ...): This method executes the provided code only if theOptionalcontains 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 anOptionalcontaining the value if it's present AND matches the given condition (value > 50), otherwise it returns an emptyOptional.
Save the
HelloJava.javafile.Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou 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: 75This output shows how
Optionalcan be used to handle the presence or absence of values and perform operations safely. While theif (isPresent() && get() > 50)pattern is similar to thenullcheck,Optionalprovides many other useful methods (ifPresent,orElse,filter,map, etc.) that can lead to more expressive and safer code when dealing with potentially absent values. UsingOptionalis 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.



