Optional
A value like int
cannot be null
. It must have a value. But sometimes no valid integer makes sense—instead, it should be specified as nonexistent.
With Optional
, we use a class
that "wraps" an int
(or any other value or class
). The Optional
class
can have an absent value. This is an empty()
class
.
This program uses an Optional
integer as an argument to a method. So the display()
method will work even if no Integer is ever specified.
of()
call creates a new Optional
based on the argument. It essentially wraps the argument in an Optional
class
.Empty()
creates an Optional
that wraps no value. The isPresent
method will return false.get()
to return an Optional
's value. But be careful—this will cause an exception if no value is present. Call isPresent
first.import java.util.Optional; public class Program { public static void display(Optional<Integer> value) { // Handle the Optional argument. if (value.isPresent()) { System.out.println(value.get()); } else { System.out.println("NOT PRESENT"); } } public static void main(String[] args) { // Call display with optional arguments. display(Optional.of(10)); display(Optional.empty()); } }10 NOT PRESENT
OrElse
Many helpful methods are included on Optional
. Consider the orElse
method. It will return the interior value of an Optional
, unless none exists.
getOrDefault
on a HashMap
).import java.util.Optional; public class Program { public static void main(String[] args) { // Create an empty Optional. Optional<Integer> option = Optional.empty(); // Use orElse to get value or the argument if no value is present. int result = option.orElse(100); System.out.println(result); } }100
IfPresent
This method executes a void
-returning method if a value exists within the Optional
. We use the lambda expression syntax here.
println
with "x" as the argument.void
).import java.util.Optional; public class Program { public static void main(String[] args) { // Print an optional if its value is present. Optional<Integer> option = Optional.of(10); option.ifPresent(x -> System.out.println(x)); // When the value is not present, nothing is printed. option = Optional.empty(); option.ifPresent(x -> System.out.println(x)); } }10
OfNullable
, null
valuesWe cannot use the of()
method on a null
value. Instead, we must invoke ofNullable
to get an Optional
that might wrap a null
value.
NullPointerException
if we call it with a null
argument.import java.util.Optional; public class Program { public static void main(String[] args) { String test = "cat"; // If a value may be null, use ofNullable. Optional<String> option = Optional.ofNullable(test); System.out.println(option.get()); // The of method will throw an exception on a null value. String test2 = null; Optional<String> option2 = Optional.of(test2); System.out.println(true); // Not reached. } }cat Exception in thread "main" java.lang.NullPointerException at java.util.Objects.requireNonNull(Unknown Source) at java.util.Optional.<init>(Unknown Source) at java.util.Optional.of(Unknown Source) at program.Program.main(Program.java:15)
Variable argument lists, where some arguments are not required, have been part of programming for a long time. Even C allows variable argument lists.
Optional
arguments. This can reduce code duplication.Optional
, we can avoid rewriting a method for a slightly different set of parameters.class
, we eliminate confusing "special values" in types like int
that mean "no value."The Optional
class
introduces a necessary performance penalty. As programmers, we must weigh this cost with the benefits of Optional
arguments.
Optional
values is worth consideration.This type introduces some complexity. But it may reduce other kinds of conceptual complexity, like "special values" that we use to indicate no value.