In Java, there are times when java.lang.NullPointerException occur accidentally. This article mainly introduces some of these anomaly types.
What this exception type is.
Let's take a look at the following code:
int x;
x = 10;
The first line declares a variable of the basic type int, which Java initializes to 0. That is, the value of the variable x is 0. The second line writes 10 to the memory unit where x is located, because it is the base type and replaces the original 0. Ok, it's all going well, nothing unexpected. However, when declaring a variable of a reference type, the variable is no longer a true value, but a reference, such as
Integer num;
num = new Integer (10);
Declaration statement, we declare a reference type named num (
Reference typeVariable, this variable contains not a true value, but a pointer (pointer this argument is not really accurate, because Java, do not want C C + + in the concept of pointers, and only the concept of reference). But we don't show where it is pointing, so Java points it to null, which means that I don't point to anywhere. In the second line, we create an instance of the integer type and assign it to num, so now that NUM can finally point it out. You can then use this pointer to manipulate the object (. operation).
However, if we declare a variable (a reference type) without an assignment statement, we use the variable directly, as follows:
Object obj = null;
System.out.println (Obj.tostring ());
That's the problem, so the obj variable is like a headless fly and doesn't know where to point. And you call Obj.tostring () is actually command obj, give me the implementation of toString () this method. God, I don't know where to go, how I know how to do it. In other words, the virtual machine cannot find the ToString code of the object that obj is referring to, and throws a NullPointerException exception.
What situation next appears npe.
In Sun's official document, several cases of throwing NPE are listed:
Calling the instance method of a Null object
Accessing or modifying the field of a null object.
Taking the length of 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.
Detailed can refer to: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/NullPointerException.html
Reference: 1. A discussion on the StackOverflow: http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception
2. Several posts: http://isagoksu.com/2009/development/java/how-to-avoid-nullpointerexceptions-npe/
Http://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html