What is NullPointerException (java.lang.NullPointerException) and why does it occur?
Is there any method that can be used to prevent a program from terminating abnormally due to NullPointerException?
java nullpointerexception
Declaring a reference variable creates a pointer to the object. That is, the reference variable stores the address (reference value) of the object. Suppose you declare a variable of int type, which is a pristine type (default type), as follows:
int x; x = 10;
In the first statement in this example, the variable x is declared int type, and Java initializes the value of this variable to zero (if variable x is defined as a field of class). And if you assign a value of 10 to that variable x using the substitution operator, like the second statement, the value of 10 is written to the memory position that the variable name x points to.
However, when you declare a variable of reference type, it is treated differently. Take a look at the following code:
Integer num;
num = new Integer(10);
num in variables are not saving the primitive value declared by the name. Instead, reference, reference type, as a wrapper class named type is the variable, is to save the address (reference value). The first statement is yet to see what defines the Java because the parameters null for initialization (However, when variable is defined as a field in a class is num). This is, which means "I don't see anything.".
The second statement uses the keyword new to create an Integer class object and stores the address (reference value) of the object in a variable called num. You can use variables that create objects and store their reference values to access them. At this point, use the . operator.
If you declare a variable of reference type and do not create an object (i.e., if you do not save the object's reference value to that variable), an exception occurs. In other words, if you attempt to access an object in that class using the num variable before the object is created, a nullPointerException occurs. In most cases, the compiler will recognize the problem and notify you with a path message. "num variable not initialized yet".
For the following methods,
public void doSomething(Integer num) { // // do something to num }
If you call as follows,
doSomething(null);
The value of the num variable is null. NullPointerException occurs when you attempt to access a field or method of an object using a num variable with these null values. The best way to prevent this exception from occurring is to check if you are storing the null value before using the reference variable, as follows:
public void doSomething(Integer num) { if(num != null) { // // do something to num } }
© 2024 OneMinuteCode. All rights reserved.