When you declare a variable of a reference type, you actually create a reference to an object of this type. Consider the following code to declare a variable of type int:
int x; x = 10;
In this example, the variable x is of type int and Java initializes it as 0. When you assign a value of 10 to the variable (second line), this value is stored in the memory location referenced by x .
But when you declare a reference type, the process looks different. Look at the following code:
Integer num; num = new Integer(10);
The first line declares the variable num , its type does not refer to the built-in, therefore, the value is a reference (the type of this variable, Integer , is a reference type). Since you have not yet indicated what you are going to refer to, Java will assign the variable the value Null , meaning "I do not refer to anything."
In the second line, the new keyword is used to create an object of type Integer . This object has an address in memory that is assigned to the variable num . Now, with the help of the variable num you can access the object using the dereference operator . .
The exception that you are talking about in the question arises if you declared a variable but did not create an object, that is, if you try to dereference num before you create an object, you will receive a NullPointerException . In the simplest case, the compiler will detect the problem and report that
num may not have been initialized
What it says: "maybe the variable num not initialized."
Sometimes an exception is caused by the fact that the object was not really created. For example, you may have the following function:
public void doSomething(Integer num){ // Работаем с num }
In this case, the creation of the object (the num variable) lies in the calling code, that is, you assume that it was created earlier — before the call to the doSomething method. Unfortunately, the following method call is quite possible:
doSomething(null);
In this case, the value of the num variable will be null . The best way to avoid this exception is to check for equality to zero. As a result, the doSomething function should be rewritten as follows:
public void doSomething(Integer num){ if (num != null) { // Работаем с num } }
As an alternative to the previous example, you can tell the caller that the method was called with invalid parameters, for example, using IllegalArgumentException .
public void doSomething(Integer num){ if (num == null) throw new IllegalArgumentException("Num не должен быть null"); // Работаем с num }
Also, pay attention to the question “ What is stack trace and how can you find errors when developing applications with it? ".
Translation of the answer “ What is a Null Pointer Exception, and how do I fix it? » @Vincent Ramdhanie .