Optional.of
- Java course
- Advanced
- Lesson 7/82
- 5 min
Learn to wrap values with Optional.of.
Wrapping a value with Optional
Optional<T> is a container that signals whether a value is present. Using Optional instead of returning null reduces the risk of NullPointerException.
To create an Optional holding a value you use Optional.of(value). Example: Optional<String> opt = Optional.of("Hello");. This method throws NullPointerException if you pass null; it is meant for cases where you are sure the value is not null.
Empty Optional: empty
Sometimes you want to express absence explicitly. Optional.empty() returns an Optional with no value. This object is a singleton; every call returns the same instance.
Example: Optional<String> empty = Optional.empty();. This is safer than returning null; the caller sees the absence through the Optional type and handles it safely with isPresent or orElse. Returning Optional.empty() when a lookup fails is an established practice.
Practice Wrap a string with Optional.of
Declare an Optional<String> named opt; fill it with Optional.of("Hello"). Use map(String::toUpperCase) to uppercase the value and orElse("") to guard against empty. Print the result with System.out.println.
Starter code
import java.util.Optional;
// Wrap "Hello" with Optional.of
// Uppercase with map, fall back to empty string with orElse
// Print the resultSample solution
import java.util.Optional;
public class HelloOptional {
public static void main(String[] args) {
Optional<String> opt = Optional.of("Hello");
String result = opt.map(String::toUpperCase).orElse("");
System.out.println(result);
}
}Expected output
HELLO
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method throws NullPointerException when passed null?
- Optional.empty
- Optional.ofNullable
- Optional.of Correct answer
- Optional.map
Explanation: Optional.of does not accept null; ofNullable is the null-safe variant.
2 Complete the Optional.of call
Optional<String> opt = Optional.____("Merhaba");
Optional<String> opt = Optional.of("Merhaba");
Explanation: of wraps a non-null value.
3 Match the Optional concepts
| Term | Meaning |
|---|---|
Optional.of |
Rejects null |
Optional.empty |
Empty container |
Optional<T> |
Wrapper |
null |
Risky value |