Let’s start with the bad news. You will come across
NullPointerException a lot while you’re writing code.
The good news is that it’s not a big deal and typically a pretty easy fix.
Null is a fancy way of saying something is nothing, nada, zilch, or empty.
In Java when you create a new object reference, but don’t assign it a value it defaults to null. Let’s look at some code.
We’ve told Java that
s is going to hold a String, but we didn’t put a value in there. Java has to put something, so it sets
s equal to
Why does it matter?
Normally our String
s would have some methods like
substring(x, y), and
s isn’t a String. It’s a
null and nulls don’t have methods.
When you try to call a method on a
null you get a
How ‘bout some more code?
String s; System.out.println( s.length() );
We might assume that this would print out the number of characters in
s, which should be zero. But since
null it doesn’t have the
length() method and you’ll get a
How to fix it
The hardest part of fixing a
NullPointerException is usually finding what’s
Once you find it, just make sure it has a value assigned.
Null Pointer Exceptions tend to come up when you forget to initialize instance variables. Let’s look at the following class.
This code is going to blow up on line 8 when we try to add to a string to
words. It’s going to do this because at that point
null. We’ve told it that
words should be an
ArrayList, but we didn’t actually put anything into
The fix is to make sure that you initialize the instance variables. Take a look at the a fixed version.
The only difference is the addition of
words = new ArrayList<>(); on line 7. This tells Java that we want an
words to replace the
null that’s there.
words.add(s); will work and no longer throw a Null Pointer Exception.