Intermediate · Exceptions and generics · topic 30 of 60 · 20 min
Avoiding NullPointerException
Explanation
Where nulls come from
- Uninitialised object fields (default null).
- Methods that return null to mean "not found": map.get(key), a database lookup with no row.
- Data from outside: JSON fields that are missing, form fields left blank.
- Unboxing a null Integer into an int.
String city = customer.getAddress().getCity(); // NPE if getAddress() returns null
// Java 14+ helpful message:
// Cannot invoke "Address.getCity()" because the return value of "Customer.getAddress()" is nullFail fast with Objects.requireNonNull
public Order(String id, Customer customer) {
this.id = java.util.Objects.requireNonNull(id, "id must not be null");
this.customer = java.util.Objects.requireNonNull(customer, "customer must not be null");
}Return empty, not null
A method that returns a list should return an empty list (List.of()) when there is nothing, not null. Then callers can loop over the result without checking. The same goes for empty strings or empty maps where they make sense.
Optional<T>: an explicit "maybe"
Optional (Java 8) is a container that either holds one value or is empty. Returning Optional<Customer> from findByPhone tells the caller clearly "there may be no customer", and the API forces them to decide what to do.
Optional<Customer> found = repo.findByPhone("9876543210");
String name = found.map(Customer::getName).orElse("Guest"); // transform, with a default
Customer c = found.orElseThrow(() -> new IllegalStateException("Not registered")); // or fail
found.ifPresent(cust -> sendWelcomeBack(cust)); // act only if present
boolean exists = found.isPresent();
Optional<String> maybe = Optional.ofNullable(possiblyNullString); // wrap a value that may be null
Optional<String> sure = Optional.of("value"); // throws NPE if given null
Optional<String> none = Optional.empty();| Method | Use |
|---|---|
| orElse(x) | Default value (x is always evaluated) |
| orElseGet(() -> x) | Default computed only when empty |
| orElseThrow() | Get the value or throw NoSuchElementException (Java 10+); with a supplier, your own exception |
| map(f) | Transform the value if present |
| ifPresent(action) | Run code only when present |
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Avoiding NullPointerException · 1/6
In this lesson you will avoid the most common Java exception: NullPointerException.
Prefer a video by a teacher? Find free videos on “java optional tutorial avoid nullpointerexception orElse orElseThrow” on YouTube ↗
In real life: Looking up a customer by phone
At a pharmacy billing counter, the cashier enters a phone number. If the customer exists, the bill shows their name and loyalty points; otherwise it says "Walk-in customer". Returning Optional from the lookup makes the "not found" case impossible to forget.
Optional<Customer> customer = customerRepo.findByPhone(phone);
String label = customer
.map(c -> c.getName() + " (" + c.getPoints() + " points)")
.orElse("Walk-in customer");
printOnBill(label);Practice (0/3 done)
What does Optional.ofNullable(null).map(String::length).orElse(-1) return?
Which line throws an exception? 1: Optional<String> a = Optional.ofNullable(null); 2: Optional<String> b = Optional.empty(); 3: Optional<String> c = Optional.of(null); 4: String d = a.orElse("x");
Write a class CustomerRepo with a Map<String, String> from phone to name and a method Optional<String> findName(String phone). In main, print the name for a known phone, "Walk-in" for an unknown one using orElse, and show orElseThrow with a custom message.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- try-with-resources and clean-upExceptions and generics · same module
- Checked vs unchecked exceptions and throwing your ownExceptions and generics · same module
- Null safetyKotlin and Android App Development · Null safety, functions and lambdas
- Typing functions and objectsFrontend Web Development · TypeScript basics
- Parameters in depth: optional, named, ref, out, params, overloadingC# and .NET · Decisions, loops and methods
- Validating inputBackend Development · APIs and request handling
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is Optional designed for?
Answer: Method return values that may be absent
Use it as a return type.
What does Optional.empty().get() do?
Answer: Throws NoSuchElementException
Never call get() without checking.
Which is better for a method that finds orders of a customer with none?
Answer: Return an empty list
Empty collections are safe to loop over.
What does Objects.requireNonNull(x, "msg") do when x is null?
Answer: Throws NullPointerException with the message
It fails fast with a clear message.
What does x ?: 0 return when x is null?Related
Which type fits an object like { rice: 20, dal: 15, sugar: 8 } where the item names can be anything?Related
Answer: Record<string, number>
Record<string, number> means any string keys with number values.
What is the default value of an uninitialised String field?Related
Answer: null
Object fields default to null (unlike local variables, which have no default).
From Classes and objects
Where must optional parameters appear?Related
Answer: After all required ones
Required parameters come first, then the optional ones with defaults.
From Parameters in depth: optional, named, ref, out, params, overloading
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Exceptions and generics”. The module exam comes next.
- Module 6 exam: Exceptions and generics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, The collections framework. 60 topics left in the course before the final exam.