How to Fix java.lang.NullPointerException in Java

  • Last Updated: September 22, 2026
  • By: javahandson
  • Series
img

How to Fix java.lang.NullPointerException in Java

Learn how to fix java.lang.NullPointerException in Java by reading the stack trace, finding which reference is null, and fixing the actual cause.

The NullPointerException in Java, often shortened to NPE, is one of the most common exceptions a developer meets. In code it shows up as java.lang.NullPointerException. You usually see an error like this:

Console / Stack trace

Exception in thread "main" java.lang.NullPointerException
    at com.example.UserService.getUserName(UserService.java:24)
    at com.example.Application.main(Application.java:10)

Or, on newer versions of Java, you get a friendlier message:

Console / Stack trace

Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.toUpperCase()" because "name" is null

Here is the good news. An NPE is usually not hard to fix. You just need to read the stack trace and spot which object is null. Oracle describes it as an error thrown when your code uses null where an object is required. That includes calling a method or reading a field through a null reference. So let us learn it with simple examples.

1. What Does null Mean in Java?

Consider this small piece of code:

Java

String name = null;
System.out.println(name.toUpperCase());

The variable name exists, but right now it does not refer to a String object. So the call name.toUpperCase() asks Java to run a method on an object that is not there. Java cannot do that. Therefore it throws java.lang.NullPointerException.

An NPE does not simply mean that “something is null.” It means your code tried to use a null reference as if it pointed to a real object.

2. Common Situations That Cause NullPointerException

An NPE can appear in several common cases. Here are the ones you meet most often.

2.1 Calling a Method on a Null Object

Java

String name = null;
int length = name.length();

Here name is null. So name.length() throws an NPE straight away.

2.2 Accessing a Field Through a Null Object

Suppose we have a simple class and then use it like this:

Java

class Employee {
    String department;
}
 
Employee employee = null;
System.out.println(employee.department);

The problem here is not department. The real problem is employee. After all, Java must first find the Employee object before it can read the department field.

2.3 Calling Methods Through a Chain of Objects

This is where NPE debugging gets a little more interesting. Consider a chained call:

Java

String city = employee.getAddress().getCity().toUpperCase();

Three references hide inside this single line:

References on the line

employee
employee.getAddress()
employee.getAddress().getCity()

Any one of them could be null. For example, imagine employee is a valid object but its address is null. Then this part fails, because Java is really running null.getCity():

Java

employee.getAddress().getCity()

3. How to Read a NullPointerException Stack Trace

This is the most important part of debugging an NPE. Suppose you get this trace:

Console / Stack trace

Exception in thread "main" java.lang.NullPointerException
    at com.javahandson.EmployeeService.getDepartment(EmployeeService.java:35)
    at com.javahandson.EmployeeController.getEmployee(EmployeeController.java:22)
    at com.javahandson.Application.main(Application.java:10)

A stack trace shows the chain of method calls that led to the error. Do not read every line at random. Instead, start with the top line that points into your code:

Stack frame

EmployeeService.java:35

It tells you the NPE happened at line 35 of EmployeeService.java. Suppose that line holds a chained call:

Java

return employee.getDepartment().getName();

Now look at the references on that line. There are three of them:

References on the line

employee
employee.getDepartment()
employee.getDepartment().getName()

But that last expression returning null does not, on its own, cause an NPE. So the real question is simple: which reference do you touch while it is null? If employee is null, then employee.getDepartment() fails. If employee is fine but its department is null, then you call getName() on null. That is the reference to find.

💡 Interview Insight
A classic interview question is, “How do you pinpoint the null reference in a chained call?” A strong answer: do not ask which value is null. Ask which reference you touch while it is null. On a line like employee.getDepartment().getName(), a null employee breaks getDepartment(), while a null department breaks getName(). Naming that exact reference is the whole skill.

4. Helpful NullPointerException Messages in Modern Java

Older Java versions often produced a bare error like this:

Console / Stack trace

java.lang.NullPointerException
    at EmployeeService.java:35

The line number told you where it broke. But if several objects sat on the same line, you still had to work out which one was null. Java 14 introduced Helpful NullPointerExceptions, which let the JVM name the null reference more precisely. From Java 15, the JVM turns these messages on by default. So instead of a bare error, you now see this:

Console / Stack trace

java.lang.NullPointerException:
Cannot invoke "Department.getName()"
because the return value of "Employee.getDepartment()" is null

This is very useful. Java tells you directly that Employee.getDepartment() returned null. So you no longer need to guess whether employee or department caused the problem.

5. A Practical Debugging Example

Let us walk through a full example with two small classes:

Java

public class Employee {
 
    private Department department;
 
    public Department getDepartment() {
        return department;
    }
}
 
public class Department {
 
    private String name;
 
    public String getName() {
        return name;
    }
}

Now we create an Employee and print its department name:

Java

Employee employee = new Employee();
 
System.out.println(
        employee.getDepartment().getName()
);

The Employee object itself exists, so employee is valid. But we never set its department. So employee.getDepartment() returns null. Java then tries null.getName() and throws the NPE.

The real fix is not if (employee != null), because employee was never the problem. You need to find out why employee.getDepartment() returned null. For example:

Java

Department department = new Department();
 
Employee employee = new Employee();
employee.setDepartment(department);

Fix the reason the null exists, not just the line where Java happens to spot it.

6. Break Long Method Chains While Debugging

If you have a long chain like this and you get an NPE, debugging can get harder:

Java

String city =
        order.getCustomer()
             .getAddress()
             .getCity()
             .toUpperCase();

Split the chain into separate steps for a while:

Java

Customer customer = order.getCustomer();
Address address = customer.getAddress();
String city = address.getCity();
String result = city.toUpperCase();

Now you can check order, customer, address, and city one by one in your debugger. So you quickly see which variable turns null. This trick helps a lot in older Java apps. There, the NPE message may not name the exact reference for you.

7. Add a Null Check When Null Is a Valid Situation

Sometimes null is expected. For example, not every employee has a middle name:

Java

String middleName = employee.getMiddleName();

In that case you can handle null on purpose, or give a sensible default:

Java

if (middleName != null) {
    System.out.println(middleName.toUpperCase());
}
 
// or a default value
String displayName =
        middleName != null ? middleName : "";

However, this does not mean you fix every NPE by scattering null checks everywhere. Look at these deeply nested guards:

Java

if (employee != null) {
    if (employee.getDepartment() != null) {
        if (employee.getDepartment().getManager() != null) {
            // ...
        }
    }
}

This might hide a deeper problem. Maybe every employee in your model must have a department. If the department is null, ignoring it quietly lets bad data travel further into the app.

8. Use Objects.requireNonNull() for Required Values

Java gives you Objects.requireNonNull() to fail at once when a required reference is null. Oracle recommends it for parameter checks in methods and constructors. For example:

Java

public EmployeeService(EmployeeRepository repository) {
    this.repository =
            Objects.requireNonNull(
                    repository,
                    "repository must not be null"
            );
}

If someone passes null, the app fails right away with a clear message:

Console / Stack trace

java.lang.NullPointerException:
repository must not be null

This is far easier to debug than letting repository stay null and finding the problem several method calls later.

9. Be Careful With Data Coming From External Sources

Null values often enter an app through external boundaries, such as:

  • Database results
  • REST API responses and JSON payloads
  • Configuration and method arguments
  • Third-party libraries, maps, and optional fields

Look at this common example:

Java

User user = userRepository.findById(id).orElse(null);
return user.getName();

If no user exists, user becomes null. Then user.getName() throws an NPE. Instead, decide clearly what should happen when the user is not found:

Java

User user = userRepository.findById(id)
        .orElseThrow(() ->
                new IllegalArgumentException(
                        "User not found: " + id
                ));

Now the failure shows the real problem, a missing user, instead of a confusing NPE somewhere later.

10. Do Not Fix NPE by Catching It Everywhere

A common mistake looks like this:

Java

try {
    employee.getDepartment().getName();
} catch (NullPointerException e) {
    // ignore
}

This usually makes debugging harder. The error tells you the program reached a state you did not expect. If you ignore it, that broken state is still there; you just hide the evidence. Instead, ask three questions in order:

  • What was null?
  • Why was it null?
  • Should null be allowed here at all?

Those three questions usually lead you straight to the correct fix.

11. Quick Checklist for Debugging NullPointerException

When you see a java.lang.NullPointerException, work through this process:

  1. Read the exception message.
  2. Find the first stack-trace line that belongs to your own code.
  3. Note the class and line number.
  4. Open that exact line.
  5. List every object reference used on the line.
  6. Work out which reference is null.
  7. Trace backward to see where that value came from.
  8. Decide whether null is valid or a bug.
  9. Fix the source of the null, not just the crash line.
  10. Run the same scenario again and verify the fix.

For example, a modern message makes most of this instant:

Console / Stack trace

java.lang.NullPointerException:
Cannot invoke "Department.getName()"
because the return value of "Employee.getDepartment()" is null
    at EmployeeService.getDepartmentName(EmployeeService.java:42)

You already know the class is EmployeeService, the line is 42, and the null reference is employee.getDepartment(). So the next question is simple: why does this employee have no department? That is the real debugging work.

12. FAQ’s on NullPointerException in Java

Q: What causes java.lang.NullPointerException in Java?

A: It happens when your code uses an object reference that holds null as if it were a real object — for example calling a method, reading a field, or accessing an array element on a variable that was never assigned. The JVM cannot resolve the call, so it throws the exception.

Q: How do I find which reference is null in the stack trace?

A: Read the stack trace top-down. On Java 15 and above, the “Cannot invoke … because … is null” message names the exact variable for you. On older versions, open the first “at” line that belongs to your own package and check which reference on that line number can be null.

Q: What is a Helpful NullPointerException?

A: It is a JVM feature (JEP 358) added in Java 14 and enabled by default from Java 15. It adds a detailed message that names both the method call that failed and the variable that was null, so you no longer have to guess.

Q: How do I avoid NullPointerException in Java?

A: Check for null before use, return an Optional instead of null, supply a safe default with Objects.requireNonNullElse, and fail fast with Objects.requireNonNull when null signals a real bug. Fixing the source beats guarding every call site.

Q: Why is my @Autowired field null in Spring Boot?

A: The bean was never created or never scanned. Confirm the class is annotated with @Component, @Service, or @Repository, and that it sits inside a package your @SpringBootApplication actually scans. Manually instantiated objects skip injection, so their dependencies stay null too.

13. Final Takeaway

A NullPointerException in Java gets much easier once you change how you read it. Do not treat the whole stack trace as one error message. Treat it as a debugging map. Start with the line where the crash happened. Then find the object you dereference on that line. If that reference is null, Java cannot call a method on it.

With modern Java, helpful NPE messages often name the exact expression that turned null. So the whole process gets much easier.

Do not only ask, “How can I stop this NPE?” Ask, “Why is this reference null in the first place?” Fixing that reason is usually the real solution.

Further Reading

  • Error: Could Not Find or Load Main Class — Causes and Fixes
  • java.lang.ClassCastException — Why It Happens and How to Fix It
  • LazyInitializationException: could not initialize proxy — no Session
  • java.lang.StackOverflowError — Causes and Fixes

 

Leave a Comment