Sunday, February 3, 2013

NullPoiterException:

 # Null pointer exceptions

Of the things which can go wrong at run time in Java programs, null pointer exceptions are by far the most common. Recall that all values in Java programs are either scalars or references to objects, and that all variables have default values, which in the case of object references is null.

Cause:
   Thrown when an application attempts to use null in a case where an object is required. These include:
  • 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. 

Solutions: 
   1. Avoid the null pointer exception by checking if the variable is null prior to using it.

       2. Always declare variables just before where they are going to be used. 

       3. Religiously initialize (fill) arrays immediately after declaration. Arrays mostly causes NullPointerException.

       4.Return Iterators instead of Lists. This allows to return empty Iterator and the consumer need not do if-null-check. NullPointerException will not creep into this pattern.

       5. Erroneously don’t declare a variable inside a constructor, it will hide the instance variable.




Rferences:
1.Reference(a)