Java error guide
How to fix NullPointerException in Java
A NullPointerException occurs when Java code tries to use an object reference that currently points to null. The lasting fix is not simply to add a null check—it is to find why the value is missing and decide what the application should do in that situation.
What causes NullPointerException?
An object variable can exist without referring to an object. Its value is then null. Java throws NullPointerException when code attempts an operation that requires a real object.
Customer customer = null; String name = customer.getName(); // NullPointerException: customer is null
The exception commonly appears when calling an instance method, reading or writing a field, accessing an array length, unboxing a null wrapper, or synchronizing on a null reference.
Step 1: identify exactly which value is null
Read the exception message before changing the code. Modern Java versions often name the expression that was null:
java.lang.NullPointerException:
Cannot invoke "Customer.getId()" because "customer" is null
at com.example.order.OrderService.createOrder(OrderService.java:87)This message tells you that customer is null and the failure was detected on line 87. If the message is less specific, split a long expression into named variables or use the debugger to inspect each value.
For longer traces, follow the workflow in How to Read Java Stack Traces and Find the Root Cause.
Step 2: trace the value back to its source
The failing line shows where Java noticed the null. The real defect may be earlier. Work backward to find where the reference came from.
Was the caller allowed to pass null, and was that contract documented or validated?
Can the requested row be missing, and does the repository represent that result safely?
Can the field be absent or null for some status codes or older response versions?
Was the object constructed by Spring, or manually created outside the application context?
Does every constructor and code path assign the value before it is used?
Solution 1: validate required values early
If null is invalid, reject it at the boundary where it first enters the method. Objects.requireNonNull documents the requirement and produces a focused message.
void createOrder(Customer customer) {
repository.save(
new Order(customer.getId())
);
}void createOrder(Customer customer) {
Objects.requireNonNull(
customer,
"customer is required"
);
repository.save(
new Order(customer.getId())
);
}For HTTP requests, convert invalid input into a suitable client error such as 400 Bad Request rather than exposing an internal stack trace.
Solution 2: handle a legitimately missing result
Sometimes “not found” is normal. Model it explicitly instead of returning null and hoping every caller remembers to check.
Customer customer = customerRepository.findById(customerId)
.orElseThrow(() -> new CustomerNotFoundException(customerId));A Spring Data repository commonly returns Optional<Customer> from findById. Handle it with orElseThrow, orElse, map, or another operation that matches the business requirement. Avoid calling get() without checking.
Solution 3: initialize collections and fields
Prefer an empty collection when “no items” is a valid result. Callers can iterate over it safely without treating absence as an error.
List<Order> findOrders() {
if (noneFound()) {
return null;
}
return orders;
}List<Order> findOrders() {
if (noneFound()) {
return List.of();
}
return orders;
}Initialize required fields in constructors and make them final when they should never change. This prevents partially initialized objects.
Solution 4: use null-safe comparisons
Calling equals on a value that may be null causes another NPE. Put a known non-null constant first or use Objects.equals.
// Unsafe when status may be null
status.equals("ACTIVE");
// Safe
"ACTIVE".equals(status);
// Safe for two potentially null values
Objects.equals(expectedStatus, actualStatus);Solution 5: fix Spring dependency injection
A service dependency may be null when the class is created manually with new, field injection is bypassed, or a test does not initialize mocks. Constructor injection makes required dependencies explicit.
@Service
class OrderService {
private final CustomerClient customerClient;
OrderService(CustomerClient customerClient) {
this.customerClient = customerClient;
}
}Let Spring create the service, inject its constructor dependencies, and construct tests with real fakes or initialized mocks. Do not add a null check around a dependency that should always exist.
Null wrapper types and automatic unboxing
A wrapper such as Integer or Boolean can be null. Java may throw an NPE while automatically converting it to the primitive int or boolean.
Boolean enabled = null;
// Throws NullPointerException during unboxing
if (enabled) { }
// Safe and explicit
if (Boolean.TRUE.equals(enabled)) { }If the value is required, validate it. If three states—true, false, and unknown—are meaningful, handle all three explicitly.
Should you catch NullPointerException?
Usually, no. Catching NPE hides a programming or data-contract problem and may allow the application to continue with corrupted state. Catch a meaningful exception at the correct boundary, or prevent the null value from reaching the failing operation.
Returning early may stop the crash while silently dropping work. Decide whether the value is required, optional, missing because of bad input, or missing because another component failed.
How to prevent the exception from returning
- Validate required inputs at application boundaries.
- Use constructor injection for required dependencies.
- Return empty collections instead of null collections.
- Model optional lookup results explicitly.
- Add nullability annotations when your tools support them.
- Write a test for the exact input that caused the failure.
- Test missing fields and downstream “not found” responses.
- Keep internal stack traces out of public API responses.
Find the likely cause in your log
Paste a sanitized NullPointerException stack trace into Log Explainer. It highlights the useful lines and suggests the safest debugging steps without uploading or storing your log.
Open Log Explainer