Null Pointer Exception

Null pointer exceptions are the most common run time exception error arises during execution of java program.

Null Pointer Exception

Null pointer exceptions are the most common run time exception error arises during execution of java program.

Null Pointer Exception

Null Pointer Exception

     

 Null pointer exceptions are the most common run time  exception error arises during execution of java program. All values in Java programs are  references to objects, and all the value in variable are default one. Usually in the case of object references, it is null. Object references are same as pointers in C. In C pointer refers to the memory location of variable, while in a Java object reference refers to an object of known type, or be null. On making a call to a method  

y.method( );

there are two things that can be wrong, y refers to a different object or the reference of object y is null. Normally, the latter one is more common.

Rule for Debugging Null Pointer Exception

1.Point out the error in line of code.

2.Indicate the object or an array to declare null whose reference is not given.

3.Point out the reason for null.

Understand Null Pointer Exception

Suppose we have a class Wide.

class Wide
{
        private int value;

        public Wide (int v)
{
        value = v;
}

public int getValue()
{ 
       return value;
}
}
public class Large 
{

       private Wide theWide;

       public static void main(String[] args)
{
         Large inst = new Large();
        System.out.println(inst.theWide.getValue()); 
}
}

 

Obviously, when you  run this code, you  get a null pointer Exception  ,the Wide has default value of null, corresponding to the default value of  constructor for class large.

Output on Command Prompt

C:\saurabh>javac Large.java

C:\saurabh>java Large
Exception in thread "main" java.lang.NullPointerException
at Large.main(Large.java:27)

There are few things to be noticed here

1.You required to place appropriate constructor, which takes a wide as a parameter. 

   public large (Wide the Wide);

{

   the Wide= the Wide;

 

}

 

2.You required to change the main program as we are getting default constructor in it.

 

Large inst = new Large (new wide(50));

3. The Wide refers to the parameter  not to the instance variable. The only way to overcome this problem by using explicitly 'this' on the left hand side. 

    public large(Wide theWide) 
{
     this.theWide = theWide;
}

 

4. Again both side of the assignment refers to the same instance variable, because this. is redundant In order to demarcate you need to give new convention like underscore( _).

   public large(Wide _theWide)

{

    this.theWide = _the Wide;

}

A number of such small issue comes around during coding. You should checked the specific line  and check error if there might be any null references .