Optional: Correct and Incorrect Use
40 min · Intermediate
Optional<T> is a container that holds either one value or nothing, and its main job is to be a method's return type when "no result" is normal. Interviewers test whether you use it as intended or as a fancy null check. Section 8, Optional, taught it in full; this lesson revises the answers and the anti-patterns.
Topics in this lesson
- Why Optional exists
- orElse vs orElseGet: the eager-evaluation trap
- Anti-patterns: get() without a check, Optional fields and parameters
- map, flatMap, filter and ifPresentOrElse chains
- Model answer: should a method return null or Optional?
Interview questions this lesson answers
- What is Optional in Java?
- Why was Optional introduced?
- What are the ways to create an Optional?
- What is the difference between of and ofNullable?
- What is the difference between orElse and orElseGet?
- Give a real bug caused by orElse.
- What does orElseThrow do?
- Why is calling get() considered bad practice?
- Is
if (opt.isPresent()) { opt.get() }wrong? - What is the difference between map and flatMap on Optional?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.