1. Overview
In this article, we will explore the need of Optional class that was introduced in Java 8. Prior to Java 8 there were two outcomes for the method who cannot return a value. It was either to throw an Exception or return a null.
This article is part of ongoing series of Optional. Read about it more here.
Remember throwing exceptions are only for exceptional cases and also an expensive operation as entire stack trace is captured.
Returning null is simpler alternative, albeit a frustrating one. Why frustrating? Because every client calling the method needs to check whether the returned result is null or not. If client neglects to make such a check, it leads to NullPointerException.
Java 8 came up with a new solution to this problem. The solution is to wrap the result in an immutable container. If container has result, it can safely access the result else the “container is empty.” This container is implemented as a class called Optional<T>.
Optional can be in either of 2 states :
- Present i.e. Contains non-null reference to T.
- Absent or is empty. (Do not say container is null.)
Optional should be reserved as return types where there is a clear need of stating “no result” and returning null in that scenario can likely cause errors. If these conditions are not satisfied most likely using Optional would be an overkill.
2. Get max in Collection
Let us use an example to understand the need of Optional.
Scenario 1 : Return null
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { if(coll.isEmpty()) return null; //find max return candidate; }
Scenario 2 : Throw an Exception
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { if(coll.isEmpty()) throw new IllegalArgumentException("input is empty"); //find max return candidate; }
3. How to use Optional?
Returning Optional
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { if(coll.isEmpty()) return Optional.empty(); //find max return Optional.of(candidate); }
4. Using Optional
We will take a deep look at different methods provided in Optional class.
Optional<String> optStr = max(words); optStr.ifPresent(System.out::println);
If the value is absent then we can get the default value from the Optional using orElse method.
optStr.orElse(DEFAULT_VALUE);
5. Conclusion
In this article, we learnt what is Optional class and how to use it. In next articles, I will discuss about how to use the methods of Optional and more importantly how not to use them.