Optional Examples
This page was last reviewed on Dec 5, 2022.
Dot Net Perls
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.
An Optional example. 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.
Detail This creates a new Optional based on the argument. It essentially wraps the argument in an Optional class.
Detail This create an Optional that wraps no value. The isPresent method will return false.
Detail We use 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()); } }
OrElse. Many helpful methods are included on Optional. Consider the orElse method. It will return the interior value of an Optional, unless none exists.
And If no value is present, it will return the argument (much like 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); } }
IfPresent. This method executes a void-returning method if a value exists within the Optional. We use the lambda expression syntax here.
Here We introduce an identifier "x" which refers to the inner value. We call println with "x" as the argument.
Detail The method called on the right side of the lambda must be a Consumer, and return no value (it must be 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)); } }
OfNullable, null values. We cannot use the of() method on a null value. Instead, we must invoke ofNullable to get an Optional that might wrap a null value.
Warning The of method will causes a 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.
Note Some functions are expressed in a clearer way with Optional arguments. This can reduce code duplication.
Note 2 With Optional, we can avoid rewriting a method for a slightly different set of parameters.
And With this class, we eliminate confusing "special values" in types like int that mean "no value."
Performance penalty. The Optional class introduces a necessary performance penalty. As programmers, we must weigh this cost with the benefits of Optional arguments.
Tip For performance-critical methods, using separate method versions instead of 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.