java.lang.NullPointerException null pointer exception Analysis

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

When you declare a reference variable (ie an object), it is in fact to create a pointer to an object.
The following code, wherein the variable declared primitive type int:

int x;
x = 10;

In this example, the variable x is an int, Java will be initialized to zero. When he was assigned to the value 10, 10 is written to the memory location referenced X.

However, when you try to declare a reference type, it will error. The following code:

Integer num;
num = new Integer(10);

The first line declares a variable name NUM , because it is a reference type, the system defaults to copy him is null ;

In the second row, new keyword is used to instantiate an object. The pointer variable num allocated to the first row Integer target, then the pointer will be null packets.

This a NullPointerException that occurs when you declare a variable but did not create the object. So pointer are some things does not actually exist.

If you try to dereference num before creating the object, it will be reported NullPointerException. Under normal circumstances, the compiler will find the problem and let you know. num may not have been initialized (num not initialized)
"But sometimes you can not write code to create an object directly.

For example, the following methods:

public void doSomething(SomeObject obj) {
   //do something to obj
}

In this case, you do not have to create an object obj, but assumes it is created before calling doSomething () method. Note that it is possible to call this method:

doSomething(null);

In this case, obj is null. If the method is intended to object passed to do something, it is appropriate to throw NullPointerException because it is presented to the programmer's error, the programmer need this information to debug.

Alternatively, there may be a case, not only the object of this method to operate incoming objects, thus (empty parameter) may be acceptable. In this case, the parameters necessary to determine whether the null, and other implementations given conditions else. It should be explained in the document that. For example, doSomething () can be written as:

public void doSomething(SomeObject obj) {
    if(obj != null) {
       //do something
    } else {
       //do something else
    }
}

Guess you like

Origin blog.csdn.net/qq_35548458/article/details/93297641