java · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
makes a missing value impossible to miss.
When a lookup finds nothing, older code hands back null: a reference to no object at all. Nothing warns the caller. The first time they call a method on it, the program stops with a , often far from the real mistake.
An Optional is a box that is either full or empty. Optional.of(value) makes a full one, Optional.empty() an empty one, and Optional.ofNullable(x) picks for you. The return type itself now says: this might be missing.
To open it, ask isPresent(), or give a fallback with orElse("Guest"), which hands back the value when there is one and the fallback when there is not.
import java.util.Map;
import java.util.Optional;
public class Main {
static Optional<String> nicknameFor(String name) {
Map<String, String> nicknames = Map.of("Robert", "Bob", "Elizabeth", "Liz");
return Optional.ofNullable(nicknames.get(name));
}
public static void main(String[] args) {
Optional<String> found = nicknameFor("Robert");
Optional<String> missing = nicknameFor("Zainab");
System.out.println(found.isPresent() + " " + missing.isPresent());
System.out.println(found.orElse("no nickname"));
System.out.println(missing.orElse("no nickname"));
System.out.println(found);
}
} A map's get hands back null for a missing key, so ofNullable is the safe way to wrap it.
guess first
Nobody stored Peru. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> capitals = Map.of("France", "Paris", "Japan", "Tokyo");
String capital = capitals.get("Peru");
System.out.println("Looking up Peru...");
System.out.println(capital.toUpperCase());
}
}
your turn
Your turn. Return a box, not a null.
Fill line 7 with a full Optional holding word, and line 10 with an empty one.
output
press run to see what happens
fix it
Asking about kiwis crashes the shop. Can you fix it?
output
press run to see what happens
- The kiwis line throws
NullPointerException. What doesstock.gethand back for a missing item? Optional.ofrefusesnull. It is only for values you know are there.- Change
Optional.oftoOptional.ofNullableon line 6, then run.
nailed it
missing values can no longer hide. :D
- Calling a method through
nullthrowsNullPointerException. Optional.ofNullablewraps a value that might be missing.orElsegives a fallback when the box is empty.
new words in your collection
- NullPointerException
- Optional
This lesson isn’t saved. A free account remembers every lesson you finish.