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.