Java: NullPointerException

Anton Suprun
2 min readJul 13, 2021
Photo by Jacek Dylag on Unsplash

Introduction

Exceptions in Java are events that occur when there is disruption to the normal flow of the program and the null pointer exception is one of these events. The NullPointerException occurs when a reference variable should point to an object but instead it points to null. Before we get into the details thought, it is important to understand reference types and how they work in Java.

What are reference types?

Consider the following two lines:

Figure 1: Reference types

The first line declares a variable num with an Integer reference type. It does not contain a value yet; it is simply a pointer that points to nothing (null). Null indicates the absence of a value.

In the second line, the new keyword is used to create an object of type Integer and the num reference variable is instructed to point to it (it no longer points to null).

Note: Do not confuse Integer and int; these are completely different. An Integer is a reference type and an int is a primitive type. Integer is a class which “wraps” the value of a primitive type in an object.

Therefore, reference types in Java hold references (or pointers) to objects and provide a way to access objects in memory.

What causes a NullPointerException?

A NullPointerException occurs when a reference variable was declared and is trying to be used by the program but doesn’t point to anything (points to null). When a variable is being used, it is being dereferenced (typically using the . (dot) to access a method or a field of the object or using the [#] to index an array).

Note: Dereferencing simply means that the memory location the reference variable points to is being accessed.

During dereferencing, if the object is not found because the variable points to null, a NullPointerException occurs.

--

--