Let’s talk about Optional
— one of the most elegant additions in Java 8 to help us write cleaner, null-safe code.
✅ What is Optional
in Java?
Optional<T>
is a container object that may or may not hold a non-null value.
It’s Java’s answer to avoiding null
checks and NullPointerException
(NPEs).
📦 Where it lives:
import java.util.Optional;
🧠 Analogy:
Think of Optional<T>
as a box:
- If the box contains a value → use it
- If the box is empty → handle it gracefully
✅ Basic Usage
1. Create an Optional
:
Optional<String> name = Optional.of("Stanley");
2. Empty Optional:
Optional<String> empty = Optional.empty();
3. Safe wrapping (nullable value):
Optional<String> maybeName = Optional.ofNullable(getName());
🔧 Common Methods
Method | Description |
---|---|
isPresent() | Returns true if value exists |
get() | Returns the value (⚠️ throws if empty) |
orElse(T) | Returns value or default |
orElseGet(Supplier) | Lazy version of orElse |
orElseThrow() | Throws exception if empty |
ifPresent(Consumer) | Runs code only if value is present |
map(Function) | Transforms the value if present |
flatMap(Function) | Like map , but avoids nested Optional<Optional<T>> |
✅ Example
Optional<String> name = Optional.of("Stanley");
name.ifPresent(n -> System.out.println("Hello, " + n)); // Output: Hello, Stanley
String result = name.map(n -> n.toUpperCase()).orElse("UNKNOWN");
System.out.println(result); // Output: STANLEY
Optional<String> maybeNull = Optional.ofNullable(null);
String result = maybeNull.orElse("Fallback");
System.out.println(result); // Output: Fallback