Summary - Optional
- Java course
- Advanced
- Lesson 12/82
- 5 min
Combine ofNullable, map and orElse to write a user finder.
Summary - Optional
In this group you covered the basics of Optional. of wraps a non-null value; ofNullable is null-safe; map and flatMap transform; orElse and orElseGet provide defaults; ifPresent and isPresent enable conditional action.
Chaining these methods produces safe code. First wrap input with ofNullable, then transform with map, finally default with orElse. This pattern removes explicit null checks and leaves readable code behind.
Practice ofNullable + map + orElse chain
Declare a String input = null. Wrap it with Optional.ofNullable(input), transform with map(String::toUpperCase) and default with orElse("EMPTY"). Print the result with System.out.println.
Starter code
import java.util.Optional;
// Wrap a possibly null input
// Map to upper, fall back to EMPTY with orElse
// Print the resultSample solution
import java.util.Optional;
public class ChainOptional {
public static void main(String[] args) {
String input = null;
String result = Optional.ofNullable(input)
.map(String::toUpperCase)
.orElse("EMPTY");
System.out.println(result);
}
}Expected output
EMPTY
When to use Optional
Optional is primarily a return type; it signals absence of a result. Using it for fields, method parameters or collection elements is discouraged.
Example: Optional<User> findById(int id). This signature tells the caller that the user may not be found. Instead of a null check you use opt.orElseThrow() or opt.ifPresent(...). This makes the code's intent clearer and reduces the risk of NullPointerException.
Practice isPresent + ifPresent + orElse together
Create an Optional<String> with Optional.of("Sam"). First check with isPresent; if present, print the value prefixed by "Has: " via System.out.println. Then use ifPresent to print with prefix "Welcome ". Finally, print the value obtained from orElse("Guest").
Starter code
import java.util.Optional;
// Wrap "Sam" with Optional.of
// Check with isPresent and print
// Print with ifPresent and orElse tooSample solution
import java.util.Optional;
public class FullOptional {
public static void main(String[] args) {
Optional<String> name = Optional.of("Sam");
if (name.isPresent()) {
System.out.println("Has: " + name.get());
}
name.ifPresent(n -> System.out.println("Welcome " + n));
System.out.println(name.orElse("Guest"));
}
}Expected output
Has: Sam Welcome Sam Sam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method calls a Supplier when the value is absent?
- orElse
- ifPresent
- isPresent
- orElseGet Correct answer
Explanation: orElseGet takes a Supplier and calls it only in the empty case.
2 Match each method with its behavior
| Term | Meaning |
|---|---|
ofNullable |
Wraps null safely |
map |
Transforms |
orElse |
Provides a default |
ifPresent |
Runs a Consumer |