Optional
A missing value (null) often causes the famous NullPointerException. Java 8 added Optional: a box that either holds a value or is empty, so you must handle both cases.
null means "no object here". The problem is that any object variable might be null, and nothing in the code tells you which ones. Call a method on a null and the program crashes with a NullPointerException - one of the most common errors in Java history.
Optional makes the "might be missing" case visible in the method's type. When a method returns Optional<Coupon>, everyone using it knows there may be no coupon, and the Optional methods (orElse, ifPresent, map) make handling both cases short and clear. Use it mainly as a return type, not for fields or parameters.
Streams return Optional when there may be no result:
Optional.ofNullable(x) when x might be null. Avoid calling get() on an empty Optional; prefer orElse or ifPresent.- Optional is a box that holds a value or is empty.
- Create with
Optional.of,ofNullableorempty. - Read with
orElse,ifPresent,map- avoidget()on empty. - Use it as a return type for "may not find a result".
