Sub topic 1
Why null Causes Trouble
Before you learn about Optional, you need to see the problem it solves. This chapter covers what null is, why it causes so many crashes, and why programmers wanted a better way to say "there might be no value here."
What null Means in Java
A reference is a variable that points to an object, such as a String or a List. It does not hold the object itself. It holds the object's location in memory.
null is a special value that means "this reference points to nothing." You can put null in any reference variable:
public class NullBasics {
public static void main(String[] args) {
String name = "Ada"; // points to a String object
String nobody = null; // points to nothing
System.out.println(name); // Ada
System.out.println(nobody); // null
}
}null is fine to store and fine to print. The trouble starts when you try to use it.
The NullPointerException
A NullPointerException (often shortened to NPE) is the error Java throws when you call a method on a null reference or read a field from one. Java has no object to work with, so it stops your program.
public class NpeDemo {
public static void main(String[] args) {
String nobody = null;
System.out.println(nobody.length()); // throws NullPointerException
}
}When you run this, the program crashes with output like this:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
at NpeDemo.main(NpeDemo.java:4)In this tiny example the bug is easy to find. Real programs are harder. The null is usually created in one place and causes the crash somewhere far away.
How null Sneaks Through a Program
Many methods return null to say "I found nothing." One example is Map.get. A Map stores pairs of keys and values. If you ask for a key that is not there, get returns null.
Here is a small program that looks up a user's email:
import java.util.Map;
public class NullTroubleDemo {
static final Map<String, String> EMAILS = Map.of(
"ada", "[email protected]",
"grace", "[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 email = findEmail("linus");
System.out.println("Email: " + email); // prints "Email: null"
System.out.println(email.length()); // throws NullPointerException
}
}Step by step, this is what happens:
findEmail("linus")asks the map for"linus". That key is missing, so the method returnsnull.- The first
printlndoes not crash. Java turnsnullinto the text"null"when it joins strings. The program printsEmail: nulland keeps going, even though something already went wrong. - The second
printlncallsemail.length(). Now Java needs a real object, so it throws an NPE.
The mistake happened at step 1. The crash happened at step 3. In a big program, those steps could be in different files, written by different people, run minutes apart. You see the crash but not its cause.
Problem 1: The Method Signature Does Not Warn You
A method signature is the first line of a method: its name, its parameters, and its return type. Look at this one:
static String findEmail(String user)It says the method returns a String. It does not say "this might return nothing." The only ways to find out are reading the method's code, reading its documentation (if anyone wrote it), or getting an NPE.
The compiler cannot help either. It does not stop you from calling .length() on a result that might be null. Java's type system treats "a String" and "maybe a String" as the same type.
Problem 2: null Checks Everywhere
The usual defense is a null check, an if statement that tests whether a reference is null before using it:
String email = findEmail("linus");
if (email != null) {
System.out.println(email.length());
} else {
System.out.println("No email on file");
}This works. But you have to remember to write it every time, and you have to know which methods need it. Forget once, and you have a bug.
It gets worse when objects contain other objects. Suppose a customer has an address and the address has a city. Any of these could be missing:
public class NestedNullDemo {
static class Address {
String city;
Address(String city) { this.city = city; }
}
static class Customer {
Address address;
Customer(Address address) { this.address = address; }
}
static Customer findCustomer(String id) {
if (id.equals("c1")) return new Customer(new Address("Oslo"));
if (id.equals("c2")) return new Customer(null); // no address
return null; // no customer
}
static String cityOf(String id) {
Customer c = findCustomer(id);
if (c != null) {
Address a = c.address;
if (a != null) {
String city = a.city;
if (city != null) {
return city.toUpperCase();
}
}
}
return "UNKNOWN";
}
public static void main(String[] args) {
System.out.println(cityOf("c1")); // OSLO
System.out.println(cityOf("c2")); // UNKNOWN
System.out.println(cityOf("c3")); // UNKNOWN
}
}The real work is one line: city.toUpperCase(). Everything else is guarding against null. Programmers sometimes call this shape a "pyramid of doom" because each check pushes the code further to the right. It is hard to read and easy to get wrong.
Problem 3: null Is Ambiguous
null can mean several different things, and the code cannot tell them apart. A HashMap lets you store null as a value, so get returning null could mean either of two things:
import java.util.HashMap;
import java.util.Map;
public class AmbiguousNullDemo {
public static void main(String[] args) {
Map<String, String> phones = new HashMap<>();
phones.put("ada", null); // Ada exists but has no phone
System.out.println(phones.get("ada")); // null
System.out.println(phones.get("linus")); // null
System.out.println(phones.containsKey("ada")); // true
System.out.println(phones.containsKey("linus")); // false
}
}Both lookups print null. To tell them apart, you need a second call to containsKey. In general, a null result might mean any of these:
| What `null` might mean | Example |
|---|---|
| The thing was not found | No user with that name |
| The thing exists but has no value | User exists, phone not given |
| The value is not loaded yet | Data still coming from a server |
| Something failed | A lookup hit an error and returned `null` |
A single value carrying four meanings forces every caller to guess.
Problem 4: null Spreads
When a method returns null, its caller often passes that null to another method, which passes it again. Each method that touches it must either check it or risk a crash. One careless return null can affect code far away. This is why the bug in NullTroubleDemo showed up so far from its cause.
The "Billion-Dollar Mistake"
The computer scientist Tony Hoare added null references to the language ALGOL W in 1965. In a 2009 talk, he called it his "billion-dollar mistake." He said null had led to huge numbers of errors, crashes, and security problems over the decades. Java inherited the same idea, and NPEs are among the most common errors Java programmers meet.
null is not evil, and Java code still uses it every day. The problem is that it is invisible in the type system and easy to forget.
What a Better Solution Needs
Looking at the four problems, a better approach should:
- Show absence in the type. A reader of the method signature should see that a value might be missing.
- Make you handle the empty case. You should not be able to use the value by accident without thinking about the missing case.
- Avoid nested checks. Chained lookups should read as a short, flat sequence of steps.
- Mean one thing. "No value" should not also mean "error" or "not loaded."
Java 8 added a class called java.util.Optional for this purpose, mainly for use as a method return type. The next chapter explains what it is and how it works.
Summary
nullmeans a reference points to nothing.- Calling a method on
nullthrows aNullPointerException. nullcan travel silently through a program and crash it far from where it started.- Method signatures do not show that a result might be
null, and the compiler does not check. - Null checks work but clutter code, especially with nested objects.
- A
nullresult can mean several different things.
Exercise
In NullTroubleDemo, the line System.out.println("Email: " + email); runs without an error even though email is null. Why does it not crash, and why is that a problem?
Show answer
When Java joins a string with a null reference using +, it turns null into the text "null" instead of calling a method on it, so no NullPointerException occurs. This is a problem because the program keeps running with a bad value. The real mistake (the missing user) goes unnoticed until a later line, email.length(), crashes far from the cause.
Exercise
Look at this signature: static String findPhone(String user). Can you tell from it whether the method might return null? What would you have to do to find out?
Show answer
No. The return type String looks the same whether or not the method can return null. You would have to read the method's code or documentation, or discover it when a NullPointerException happens. The compiler gives no warning.
Exercise
Write a null-safe version of this line, printing "No name" when name is null: System.out.println(name.toUpperCase());
Show answer
if (name != null) { System.out.println(name.toUpperCase()); } else { System.out.println("No name"); }
Exercise
A HashMap call phones.get("ada") returns null. Name two different things this could mean, and the method you could call to tell them apart.
Show answer
It could mean the key "ada" is not in the map at all, or that "ada" is in the map but its value is null. Calling phones.containsKey("ada") tells you which: it returns true in the second case and false in the first.