Java Optional Examples

This Java article uses the Optional class to specify Optional arguments to methods. The of, isPresent and empty methods are shown.
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.

Optional.of: This creates a new Optional based on the argument. It essentially wraps the argument in an Optional class.

Optional.empty: This create an Optional that wraps no value. The isPresent method will return false.

Get: 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.

Java program that uses Optional Integer 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()); } } Output 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.

And: If no value is present, it will return the argument (much like getOrDefault on a HashMap).

HashMap
Java program that uses Optional orElse 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); } } Output 100
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.

Void: The method called on the right side of the lambda must be a Consumer, and return no value (it must be void).

Println
Java program that uses ifPresent 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)); } } Output 10
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.

Caution: The of method will causes a NullPointerException if we call it with a null argument.

Exceptions
Java program that uses ofNullable, of 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. } } Output 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls