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.
String name = null;
System.out.println(name.length()); // NullPointerExceptionReading 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.
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
| Cause | Example | Fix |
|---|---|---|
| Field never initialised | private List<String> items; then items.add("a") | Create it: items = new ArrayList<>(); in the field or constructor |
| Array of objects not filled | Student[] s = new Student[3]; s[0].getName() | Fill each slot: s[0] = new Student(...) |
| Method returned null | map.get("key").trim() when the key is missing | Check the result first, or use getOrDefault |
| Constructor parameter shadows field | name = name; inside the constructor | Write this.name = name; |
| Unboxing a null wrapper | Integer count = null; int c = count; | Give the wrapper a value or use int |
How to fix it step by step
- Go to the line in the stack trace.
- Find every
.on that line: the thing on the left of a dot may be null. - Print or debug those values just before the line.
- Ask why the value is null: was it never assigned, or did a method return null?
- Fix the cause (create the object, assign the field) rather than hiding the error.
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
nullfrom your own methods. - Use
Objects.requireNonNull(x)at the start of a method to fail early with a clear message. - Use
Optionalfor 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.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.