Java Optional: Saying Maybe Without null
A phone book returns null for Omar and the next .length() crashes. Optional.ofNullable gives a box instead: Optional[555-1234] or Optional.empty. orElse hands over "no number", ifPresent runs only for Asha, and map adds +1 only when there's a number.
What you will learn
- Explain how a method that returns null can crash the caller's next line
- Return an Optional with Optional.ofNullable instead of null
- Take the value out with orElse, ifPresent or orElseThrow
- Change the value inside with map, which skips an empty box
Before you start
- Java lambdas and functional interfaces
- Java maps: HashMap, LinkedHashMap and TreeMap
Think of a phone book. You look up someone who isn't in it. What should you get back? Optional is Java's way of saying "maybe there's a value, maybe there isn't", without using null.
A missing name gives back null
package org.studyeasy.s05l08;
import java.util.Map;
public class Ex01_NullProblem {
static Map<String, String> phones = Map.of("Asha", "555-1234");
// No phone for this name: Map.get gives back null
static String findPhone(String name) {
return phones.get(name);
}
public static void main(String[] args) {
System.out.println(findPhone("Asha"));
System.out.println(findPhone("Omar"));
System.out.println(findPhone("Asha").length());
}
}
555-1234
null
8
Only Asha is in the phone book. For Omar, Map.get returns null, and println just shows the word null. No error yet. Add findPhone("Omar").length() and the program stops with a NullPointerException: it cannot invoke String.length() because the return value of findPhone is null. A method that can return null leaves every caller to remember the check. Forget it once, and the program stops.
Return a box, not null
// The return type says it: there may be no phone
static Optional<String> findPhone(String name) {
return Optional.ofNullable(phones.get(name));
}
System.out.println(findPhone("Asha"));
System.out.println(findPhone("Omar"));
System.out.println(findPhone("Asha").isPresent());
System.out.println(findPhone("Omar").isPresent());
Optional[555-1234]
Optional.empty
true
false
The return type is now Optional<String>, so the method itself tells you there may be no phone. Optional.ofNullable wraps the result: a value goes into the box, and null becomes an empty box. isPresent asks the box. Nothing crashed. An Optional isn't a String, though: String phone = findPhone("Asha"); won't compile.
Take the value out, or hand over a fallback
// orElse: the value, or this fallback when the box is empty
System.out.println(findPhone("Asha").orElse("no number"));
System.out.println(findPhone("Omar").orElse("no number"));
// ifPresent: run this only when there is a value
findPhone("Asha").ifPresent(p -> System.out.println("Call " + p));
findPhone("Omar").ifPresent(p -> System.out.println("Call " + p));
// orElseThrow: the value, or an exception if it is missing
System.out.println(findPhone("Asha").orElseThrow());
555-1234
no number
Call 555-1234
555-1234
Asha's box is full, so orElse gives the value and the fallback isn't used. Omar's box is empty, so it hands over "no number". ifPresent takes a lambda and runs it only when there's a value: for Omar, nothing prints and there's no error. orElseThrow gives the value, or throws NoSuchElementException for an empty box.
map skips an empty box
Optional<String> asha = findPhone("Asha");
Optional<String> omar = findPhone("Omar");
// map: change the value inside, only if there is one
System.out.println(asha.map(p -> "+1 " + p));
System.out.println(omar.map(p -> "+1 " + p));
// map first, then unwrap once with orElse
System.out.println(asha.map(p -> "+1 " + p).orElse("no number"));
System.out.println(omar.map(p -> "+1 " + p).orElse("no number"));
// an empty box skips the map and the ifPresent
omar.map(p -> "+1 " + p).ifPresent(System.out::println);
Optional[+1 555-1234]
Optional.empty
+1 555-1234
no number
This map isn't the Map data structure; it changes the value inside the box. The lambda puts a +1 country code in front. For Asha it runs and a new box comes out. For Omar it doesn't run at all, and an empty box passes straight through. Then orElse unwraps once, at the end. The last line prints nothing, because the empty box skips both steps. (System.out::println is a method reference, shorthand for p -> System.out.println(p).)
Recap
| Method | Full box | Empty box |
|---|---|---|
Optional.ofNullable(x) | wraps x | made from null |
isPresent() | true | false |
orElse(fallback) | the value | the fallback |
ifPresent(lambda) | runs it | does nothing |
orElseThrow() | the value | NoSuchElementException |
map(lambda) | a new box | stays empty |
Streams return Optionals too, for example from max; see streams: filter, map, reduce.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Lambdas and Functional Interfaces
A six-line anonymous Discount becomes total -> total * 0.85. Lambdas with no, one and two parameters show which brackets and braces can go, a Runnable job runs between START and DONE, and two Comparator lambdas sort students by marks, then by name.
Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
Four ready-made sockets for lambdas: Predicate tests 20 >= 18, Function turns 5 into 15, Consumer prints Hello, Priya, Supplier hands back Monday. Then isPositive.and(isEven), isEven.negate() and multiply.andThen(addFive), which turns 3 and 4 into 17.
Java Streams I: filter, map and reduce
Picture a conveyor belt: 4, 7, 2, 9, 5 ride through filter(n -> n > 4) and map(n -> n * 10) and come out as [70, 90, 50]. Then sorted and count on exam scores, and reduce folding a cart of 499, 1299, 250 and 799 into a 2847 bill.
Java Streams II: Collectors, groupingBy and flatMap
Six sales feed every example. toList and joining give [Emma, Jake, Sofia] and "North / South / West", groupingBy with counting and summingInt gives a count and a total per region, flatMap pours three orders' items into one list, and mapToInt sums 5400.
