Sub topic 1
Why null Causes Trouble
The Problem with null
In Java, null is a special value that means "no object here." A method can return null when it has nothing to give back. The trouble is that the method's signature does not warn you. If you forget to check and call a method on null, Java throws a NullPointerException. A NullPointerException is an error that crashes your program at run time.
public class NullDemo {
static String findNickname(String name) {
return null; // no nickname found
}
public static void main(String[] args) {
String nick = findNickname("Ada");
System.out.println(nick.length()); // NullPointerException
}
}The compiler accepts this code without complaint. The bug only appears when the program runs.
Meet Optional: A Container for Maybe-Values
Optional is a class in java.util. It is a small box that holds either one value or nothing. When a method returns Optional<String>, its signature tells you that a value might be missing. That reminds you to handle the empty case.
Creating Optionals
You can make an Optional in three ways:
| Method | Use it when |
|---|---|
| `Optional.of(value)` | The value is never null. It throws an error if the value is null. |
| `Optional.ofNullable(value)` | The value might be null. |
| `Optional.empty()` | You have no value. |
Checking Whether a Value Is Present
isPresent() returns true if the box holds a value. isEmpty() returns true if the box is empty. isEmpty() needs Java 11 or later.
import java.util.Optional;
public class CreateDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
Optional<String> none = Optional.empty();
String fromEnv = System.getenv("USER_NAME"); // may be null
Optional<String> maybe = Optional.ofNullable(fromEnv);
System.out.println(name.isPresent()); // true
System.out.println(none.isEmpty()); // true
System.out.println(maybe.isPresent()); // depends on your environment
}
}Exercise
A method returns a String that may be null. Which factory method should you use to wrap it, and what does isEmpty() return if the String was null?
Show answer
Use Optional.ofNullable. If the String was null, the Optional is empty, so isEmpty() returns true.