Total Pageviews

Monday, December 19, 2011

NullPointerException - Exception of Exceptions


Once or more, but every java programmer faced NULL POINTER EXCEPTION and we generally ignore its cause. But a slight caution can harbinger in minimizing the chances of NPE. Lets understand it in deep.


When we declare a reference variable (i.e. an object, or sa instance of a class) we are really creating a pointer to an object. Consider the following code where we declare a variable of primitive type int:

In this example the variable x is an integer and Java will initialize it to 0. When we assign it to 10 in the second line our value 10 is written into the memory location pointed to by x.


But, when we try to declare a reference type something different happens. Take the following code:
The first line declare a variable named num, but, it does not contain a primitive value. Instead it contains a pointer (because the type is Integer which is a reference type). Since we did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".


In the second line the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable num is assigned this object. We can now reference the object using the dereferencing operator . (a dot).


NPE occurs when we declare a variable but did not create an object. If we attempt to dereference num BEFORE creating the object we get a NullPointerException. In the most trivial cases the compiler will catch the problem and let us know that "num may not have been initialized" but sometime we write code that does not directly create the object.


For instance we may have a method as follows:
in which case we are not creating the object num, rather assuming that is was created before the doSomething method was called. Unfortunately it is possible to call the method like this:
In which case num is null. The best way to avoid this type of exception is to always check for null when you did not create the object yourself. So doSomething should be re-written as:
To conclude, we can say NPE occur when we try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NPE.