NullPointerException

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.

What’s null?

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.

String s; 

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 null.

Why does it matter?

Normally our String s would have some methods like length(), substring(x, y), and indexOf(x). But 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 NullPointerException.

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 s is null it doesn’t have the length() method and you’ll get a NullPointerException.

How to fix it

The hardest part of fixing a NullPointerException is usually finding what’s null.

Once you find it, just make sure it has a value assigned.