Java null pointer exception

  • Post author:
  • Post category:Java / Java Advanced
  • Post last modified:July 7, 2021
  • Reading time:2 mins read

Today we will learn, What is a NullPointerException, and how do I fix it? So, let’s start:

What is NullPointException

NullPointException is a RunTimeException. NullPointException is thrown when the value of a reference variable or object is null.

When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign the value of 10 on the second line, your value of 10 is written into the memory location referred to by x.

But, when you try to declare a reference type, something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you have not yet said what to point to, Java sets it to null, which means “I am pointing to nothing“.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the pointer variable num is assigned to that Integer object.

The NullPointerException occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you are pointing to something that does not actually exist.

Is it clear?

How to avoid NullPointException?

Please read This article for better understanding:

java null pointer exception

Hope it helps