What Is Null Pointer Exception In Java and How To Fix? – POFTUT

What Is Null Pointer Exception In Java and How To Fix?


Java programming language provides the Null Pointer Exception type in order to handle object creation related errors and misuse. In this tutorial, we will learn what is Null Pointer Exception, its causes and How To Fix it?

Null Pointer Exception

Java is an object-oriented programming language. Java provides different objects in order to create and use. In order to use an object, it should be initialized properly. If the object not initialized properly and try to be used it will throw a Null Pointer Exception.

In the following code, we define an Integer object with the variable name num.  Then we initialize it with the new Integer(10) line. If we do not initialize the variable num and try to use it we will get a Null Pointer Exception.

class HelloWorld
{
        public static void main(String args[])
        {
                Integer num = null;

                int new_var = num.intValue() ;

                System.out.println(new_var);
        }
}

We can see that the following information about the null pointer exception is provided when the exception is thrown.

  • `Thread name` is the thread name where the exception occurred.
  • `Exception type` is the exception name with the full class name which is `java.lang.NullPointerException` in this example.
  • `The class name` where the name of the class where the exception occurred which is `HelloWorld` in this example.
  • `The function name` is the function name where the exception occurred which is `main` in this example.
  • `The line number` is the source code line number where the exception occurred which is 9 in this case.

Causes Of Null Pointer Exception

Null pointer exception can occur in different ways with different causes. But we can list them like below in general.

  • Calling the instance method of a null object.
  • Accessing or modifying the field or a null object.
  • Taking the length of the null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.
LEARN MORE  What Is Segmentation Faults and Causes?
Causes Of Null Pointer Exception
Causes Of Null Pointer Exception

Solutions For Null Pointer Exception

The null pointer exception can be fixed or solved just by properly initializing the given object which will set an instance for the object. So the object will have an instance and will not null which is the cause of the Null Pointer Exception. In the following example, we will initialize the variable named num which is an Integer type.

class HelloWorld
{
        public static void main(String args[])
        {
                Integer num = 10;

                int new_var = num.intValue() ;

                System.out.println(new_var);
        }
}

Leave a Comment