Sub topic 1
Why null Causes Trouble
Before you learn Optional, you need to see the problem it solves. That problem is null. This chapter shows where null comes from, why it breaks programs, and why the fixes people usually reach for don't hold up well.
What null Means
In Java, null is a special value. It means "this variable points to no object." A variable of any object type, such as String, can hold null.
Methods often return null to say "I found nothing." For example, Map.get returns null when the key is not in the map.
The Crash: NullPointerException
A NullPointerException (often shortened to NPE) is an error. Java throws it when you call a method on a variable that holds null. There is no object, so there is no method to run.
Here is a small program that looks fine but crashes:
import java.util.Map;
public class NullDemo {
static final Map<String, String> EMAILS =
Map.of("ada", "[email protected]");
static String findEmail(String user) {
return EMAILS.get(user); // returns null if the user is unknown
}
public static void main(String[] args) {
String found = findEmail("ada");
System.out.println(found.toUpperCase()); // [email protected]
String missing = findEmail("bob");
System.out.println(missing.toUpperCase()); // throws NullPointerException
}
}The first lookup works. The second returns null, and calling toUpperCase() on it stops the program.
Why This Is Hard to Spot
Look at the method signature again:
static String findEmail(String user)Nothing in it says "this might give you nothing." The return type is just String. To know that null can come back, you have to read the code inside the method or its documentation. Most people don't, so they forget to check.
The compiler can't help either. It accepts missing.toUpperCase() without any warning. You only find the bug when the program runs, sometimes long after the code shipped.
The Usual Fix: Null Checks
The common fix is to check for null before using the value:
import java.util.Map;
public class NullCheckDemo {
static final Map<String, String> EMAILS =
Map.of("ada", "[email protected]");
static String findEmail(String user) {
return EMAILS.get(user);
}
public static void main(String[] args) {
String email = findEmail("bob");
if (email != null) {
System.out.println(email.toUpperCase());
} else {
System.out.println("No email found");
}
}
}This works. It prints No email found. But it has real weaknesses:
| Problem | What happens |
|---|---|
| Easy to forget | Nothing forces you to write the check. |
| Spreads everywhere | Every caller must repeat the same `if`. |
| Hides meaning | `null` can mean "not found," "not set yet," or "error." |
| Grows messy | Chained lookups become deeply nested `if` blocks. |
The last point gets worse fast. Suppose you need a customer's address, then the address's city. Each step might be null, so you end up with checks inside checks.
What We Want Instead
A better approach would:
- Make it obvious from the method's return type that a value might be missing.
- Make it hard to use a missing value by accident.
- Give short, readable ways to handle the "nothing here" case.
Java's Optional class is designed to meet these goals. The next chapter introduces it.
Exercise
The method String findPhone(String name) sometimes returns null. A caller writes findPhone("li").length(). What happens when no phone exists for "li", and why didn't the compiler warn about it?
Show answer
Java throws a NullPointerException, because length() is called on null and there is no object to run it on. The compiler gave no warning because the return type String doesn't say a value can be missing, and Java lets any object variable hold null.
Exercise
Name two drawbacks of fixing null problems by adding if (x != null) checks everywhere.
Show answer
Any two of these: the checks are easy to forget, they get repeated in every caller, null doesn't say why the value is missing, and chained lookups turn into deeply nested if blocks.