← Learning Hub
Beginner

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.

Example
You can edit this code.

Streams return Optional when there may be no result:

Example
You can edit this code.
Use Optional.ofNullable(x) when x might be null. Avoid calling get() on an empty Optional; prefer orElse or ifPresent.
Key points
  • Optional is a box that holds a value or is empty.
  • Create with Optional.of, ofNullable or empty.
  • Read with orElse, ifPresent, map - avoid get() on empty.
  • Use it as a return type for "may not find a result".

📝 Test yourself

1. What problem does Optional help avoid?
2. What does orElse("X") return for an empty Optional?
3. Fill in the method that makes an empty Optional:
Optional.()