Java: NullPointerException

Photo by Jacek Dylag on Unsplash


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.




Computer Science Student, Programming Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Auto-updating web service in Dart

A Complete Guide to Deploying Elixir & Phoenix Applications on Kubernetes — Part 1: Setting up…

Windows Insets + Fragment Transitions

A simplified synopsis of Zoom

Who Should Take Architectural Decisions?

How to Build User and Admin in Ruby on Rails

A brief tour of lists in Scala and algorithmically processing them in SICP exercises

How to work in 2020

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anton Suprun

Anton Suprun

Computer Science Student, Programming Enthusiast

More from Medium

Java Maps- My toolbox

Object Oriented Programming with Java

Java Strings: A comprehensive

Arithmetic Exception in Java