Skip to main content

NullPointerException in Java explained

6 min readUpdated

A NullPointerException (NPE) is the error Java throws when your code tries to use an object that does not exist. It is the most common runtime error in student projects, and once you know where to look it is usually quick to fix.

What null actually means

A variable of a class type (such as String or Student) does not hold the object itself. It holds a reference, an arrow pointing to an object. null means the arrow points nowhere. Calling a method or reading a field through that arrow fails, because there is nothing at the other end.

The smallest possible NPEjava
String name = null;
System.out.println(name.length());   // NullPointerException

Reading the error message

Recent Java versions print a helpful message that names the exact thing that was null, plus the file and line number. Read the first line of the stack trace that points to your code: that is where to start.

Example stack tracetext
Exception in thread "main" java.lang.NullPointerException:
  Cannot invoke "String.length()" because "name" is null
    at Main.main(Main.java:4)

The most common causes

CauseExampleFix
Field never initialisedprivate List<String> items; then items.add("a")Create it: items = new ArrayList<>(); in the field or constructor
Array of objects not filledStudent[] s = new Student[3]; s[0].getName()Fill each slot: s[0] = new Student(...)
Method returned nullmap.get("key").trim() when the key is missingCheck the result first, or use getOrDefault
Constructor parameter shadows fieldname = name; inside the constructorWrite this.name = name;
Unboxing a null wrapperInteger count = null; int c = count;Give the wrapper a value or use int

How to fix it step by step

  1. Go to the line in the stack trace.
  2. Find every . on that line: the thing on the left of a dot may be null.
  3. Print or debug those values just before the line.
  4. Ask why the value is null: was it never assigned, or did a method return null?
  5. Fix the cause (create the object, assign the field) rather than hiding the error.
A classic constructor bug, fixedjava
public class Student {
    private String name;

    public Student(String name) {
        this.name = name;   // without 'this.' the field stays null
    }

    public int nameLength() {
        return name.length();
    }
}

Preventing NPEs

  • Initialise fields where you declare them or in the constructor.
  • Compare with a known non-null value first: "yes".equals(answer) cannot throw, answer.equals("yes") can.
  • Return an empty list instead of null from your own methods.
  • Use Objects.requireNonNull(x) at the start of a method to fail early with a clear message.
  • Use Optional for a value that may honestly be missing.

Do not wrap code in try { ... } catch (NullPointerException e) {} to make the error go away. It hides the real bug and examiners and reviewers will mark it down.

Frequently asked questions

Is NullPointerException checked or unchecked?

Unchecked. It extends RuntimeException, so the compiler does not force you to catch it. You prevent it by fixing your code.

Why does my array of objects give a NullPointerException?

new Student[3] creates three empty slots, all null. You must create a Student for each slot before calling methods on it.

Can primitives like int be null?

No. Only references can be null. But a wrapper like Integer can, and converting a null Integer to int throws an NPE.

Practise this, step by step

Short lessons with quizzes, practice and interview questions, from your first program to job-ready.

Java Programming course: syllabus and 1:1 mentoringCore Java from zero to OOP, collections, streams, files and threads.