NullPointerException — Causes and Prevention
Fast recall
Quick revision
Core answer
Optional is mainly useful as a return type, not a universal replacement for null.Interview-ready guide
Interview answer
NullPointerException happens when you try to use a reference variable that's pointing to null instead of an actual object.
It's the most common runtime exception you'll see in Java. The JVM throws it when you call a method or access a field on null.
For example, if you do String name equals null and then call name dot length, you get an NPE because there's no String object to call length on. The modern way to prevent this is using Optional. When a method might not have a result, like looking up a user by ID, you return Optional of User instead of just User.
That way the caller sees in the method signature that the value might be absent, and they're forced to handle it with methods like orElse or ifPresent. You also prevent NPEs by validating inputs at boundaries. In a REST controller, check if the incoming ID parameter is null before passing it to your service layer.
In constructors, use Objects dot requireNonNull to fail immediately if someone tries to inject a null dependency. One mistake freshers make is thinking you should just add null checks everywhere. That's a code smell.
If you're checking for null constantly, it means you're allowing nulls too deep into your code. Design your methods to return Optional or non-null values, and validate at entry points. That way the rest of your code can assume values exist and be much cleaner.
In Spring Boot apps, constructor injection helps a lot because Spring won't create the bean if it can't satisfy the dependencies, so your service fields are never null.
NullPointerException — Causes and Prevention
Direct Answer
A NullPointerException occurs when Java needs an object or array but the reference is null—for example, invoking a method, reading a field or array length, indexing a null array, synchronizing on null, or unboxing a null wrapper. Prevent it by defining null contracts, validating required inputs, initializing state, and representing optional results clearly; Optional is mainly useful as a return type, not a universal replacement for null.
Code Example
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) {
this.repository = repository;
}
// Modern approach: Optional makes nullability explicit
public Optional<Order> findOrder(Long orderId) {
if (orderId == null) {
return Optional.empty(); // guard at entry point
}
return repository.findById(orderId);
}
// Safe usage with Optional
public String getOrderStatus(Long orderId) {
return findOrder(orderId)
.map(Order::status) // only called if Order exists
.orElse("NOT_FOUND"); // fallback when null
}
}
Common Mistakes & Pitfalls
- Checking for null after every call: Freshers scatter if (value != null) checks everywhere instead of designing methods to return non-null values or Optional. This makes code unreadable and misses the root cause.
- Returning null from methods: Returning null forces every caller to remember to check, creating NPE landmines throughout the codebase. Return Optional or an empty collection instead.
- Not validating constructor parameters: Allowing null to be stored in fields during object creation means the NPE happens far from the source, making debugging harder.
Check your understanding
Answer these without looking back at the article.
- What is Optional in Java and when should you use it?
- What is the difference between an unchecked and a checked exception?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.