Null vs ZeroLet’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.

Common Cause

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 words is null. We’ve told it that words should be an ArrayList, but we didn’t actually put anything into words yet.

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 ArrayList in words to replace the null that’s there.

Now words.add(s); will work and no longer throw a Null Pointer Exception.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>