Skip to content

Intermediate · Exceptions and generics · topic 30 of 60 · 20 min

Avoiding NullPointerException

Explanation

NullPointerException (NPE) happens when you call a method or read a field on null. Prevent it by validating inputs with Objects.requireNonNull, returning empty collections instead of null, and using Optional<T> as a method return type when a value may be absent. Optional offers orElse, orElseThrow, map and ifPresent; it is not meant for fields or parameters.

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.
java
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 null
Modern JDKs print helpful NPE messages that name exactly what was null.

Fail fast with Objects.requireNonNull

java
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");
}
The error appears at construction, with a clear message, instead of much later.

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.

java
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();
MethodUse
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
Careful: Do not call optional.get() without checking; it throws NoSuchElementException when empty, which just moves the NPE problem. And do not use Optional for fields, method parameters or collections (Optional<List<…>>); it was designed as a return type. Never return null from a method declared to return Optional.
Think of it like this: Optional is like a gift box with a window: you can see whether something is inside before you open it, and you decide in advance what to do if it is empty ("then give me a chocolate instead"). A plain null is a closed box that explodes when you open it empty.
Tip: Annotations like @Nullable and @NonNull (from libraries such as JSpecify) plus IDE inspections can warn about possible nulls while you type.

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

Avoiding NPE

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.

java
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)

Task 1 · Question

What does Optional.ofNullable(null).map(String::length).orElse(-1) return?

Task 2 · Question

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");

Task 3 · Practice

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

Question 1

1.What is Optional designed for?

Question 2

2.What does Optional.empty().get() do?

Question 3

3.Which is better for a method that finds orders of a customer with none?

Question 4

4.What does Objects.requireNonNull(x, "msg") do when x is null?

Read more (free)

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

Answer: 0

Elvis returns the right side when the left is null.

From Null safety

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.

From Typing functions and objects

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

  1. This is the last topic of “Exceptions and generics”. The module exam comes next.
  2. Module 6 exam: Exceptions and generics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, The collections framework. 60 topics left in the course before the final exam.

← Previous: Generics