Command Palette

Search for a command to run...

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

Creating an Optional and getting the value out

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?

Creating an Optional and getting the value out Java 11+
Sign in to run this example in your browser.

Expected output

Optional[asha@mail.in] / Optional.empty
isPresent: true, isEmpty: true
orElse:      no email
orElseGet:   generated@mail.in
orElseThrow: asha@mail.in
send to asha@mail.in
nothing to send for zoya
caught: unknown user: zoya
Optional.of(null) throws NullPointerException