Command Palette

Search for a command to run...

Back to the lesson: Topic 10.7 — Optional
Core Java · Example 2 of 4 Java 8+

orElse runs its argument even when it isn't needed

The first call computed a default and threw it away. With a database lookup instead of a print, that's a real cost on every call.

Optional<T> is a box that holds either one value or nothing, used as a method's return type to say "there may be no result". Instead of returning null and hoping the caller checks, you return an Optional and the caller must decide what happens when it's empty, with orElse, orElseThrow, map and friends.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static Optional<Integer> parseAge(String s) that returns empty for non-numbers and for ages outside 0..150. Print the result for "42", "abc" and "200", using orElse(-1).

02

Given Map<String, String> managers (employee to manager), write a method that returns the manager's manager as Optional<String>, using ofNullable and map. Test it on a three-level chain and on someone at the top.

03

From List.of("7", "x", "12", "", "5"), use your parseAge and flatMap(Optional::stream) to print the sum of the valid ages.

Explain it without notes

01

Why was Optional added, and what is it meant to be used for?

02

What's the difference between orElse and orElseGet?

03

When do you use map and when flatMap on an Optional?

04

Where should you not use Optional, and why?

orElse runs its argument even when it isn't needed Java 8+
Sign in to run this example in your browser.

Expected output

orElse on a present value:
  (computing default...)
  result cached
orElseGet on a present value:
  result cached
orElseGet on an empty value:
  (computing default...)
  result default
default computed 2 times