NullPointerException

Null vs Zero

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. It’s not zero, it’s not an empty string, it’s not an empty list. It’s just nothing.

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.

import java.util.ArrayList; 

public class Demo {
  private ArrayList<String> words; 
  
  public Demo( String[] theWords ) {
      for (String s: theWords) {
        words.add(s);  
      }
  }
  
  public static void main( String... args ) {
    Demo d = new Demo( "here are some words" ); 
    System.out.println( words ); 
  }
}

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.

import java.util.ArrayList; 

public class DemoFixed {
  private ArrayList<String> words; 
  
  public Demo( String[] theWords ) {
      words = new ArrayList<>();
      for (String s: theWords) {
        words.add(s);  
      }
  }
  
  public static void main( String... args ) {
    DemoFixed d = new DemoFixed( "here are some words" ); 
    System.out.println( words ); 
  }
}

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.

Ask Question