java.lang.NullPointerException exception is one of the most popular errors in Java and it is caused by so many issues.

One of such issues is when an objected is initiated to a Null value and then its reference is used to call a method or a variable.

Example is in the code below.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package checkingnullpointers;

/**
 *
 * @author adaba
 */
public class CheckingNullPointers {

    //define some fields
    private String field1  = null;
    private String field2  = null;
    
    public String getField1(){
        return field1;
    }
           
    public void setField1(String field1){
        this.field1 = field1;
    }
    
    public String getField2(){
        return field2;
    }
    
    public void setField2(String field2){
        this.field2 = field2 ;
    }
    /**
     * method to greet
     * 
     */
    public void greet(){
      System.out.println("Hello World");
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        try{
        // TODO code application logic here
        CheckingNullPointers chk = new CheckingNullPointers();
        //CheckingNullPointers chk = null;
        //chk.greet();
        //initialise field1
        chk.setField1("field1Value");
        
        //do something
        chk = doSomething();
        
        //initialize field2
        chk.setField2("field2Value");
        
        }catch(Throwable any){
                System.out.println("Java Error" + any);
                any.printStackTrace();
                        }
        
          
        
    }
    
    // do something
        private static CheckingNullPointers doSomething(){
            return null;
        }
            
}

// the

In the code above the line at

chk.setField2("field2Value");

throws java.lang.NullPointerException because the doSomething() method sets the CheckingNullPointers instance to Null and then the Null instance is being used to call setField2(String field2) which then throws the exception. 

It is always good to check if the instance is not Null before using it to call a method or variable.

 

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *