Wednesday, September 26, 2012

NullPointerException in Java - A nemesis of Programmer - Tips to fix and prevent

NullPointerException in Java is a unchecked Exception defined in java.lang package and comes when a member of a an object either field or method is called on a object which is null. null is a keyword in Java which means nothing and calling method on Object whose value is null will result in NullPointerException. Since default value of Object is null, if you call any method or access any field on an Object which is not initialized will throw NullPointerException. Some programmer get confused with name as well, Since Java does not support pointers, How can you have NullPointerException in Java? Well java.lang.NullPointerException doesn't have anything to do with pointers, it just an Exception in Java. If you look at it more deeply, NullPointerException is an unchecked Exception and it's not mandatory to provide Exception handling code for it using try, catch and finally. In fact most of NullPointerException comes because of programming errors. See most common cause of NullPointerException to find out most common scenario where NullPointerException comes in Java. In this Java article we will not only see What is NullPointerException but also How to avoid NullPointerException and How to fix java.lang.NullPointerException in Java.


When NullPointerException occurs in Java
What is NullPointerExcpetion in Java When Why HowIn last section we saw that What is java.lang.NullPointerException and finds that NullPointerException occurs when we call method or access members on an Object which is null, i.e. either its not initialized or it has been set null explicitly. This is fundamental of NullPointerException but it manifest itself in many places e.g.

1) NullPointerException comes when you try to use an Object in synchronized keyword which is null as shown in following example :

Object lock = null;
synchronized(lock){ } //NullPointerException, can not synchronized with null object


2) Similarly if you try to access any element from Array, which is null will result in NullPointerException.

How to solve NullPointerException in Java

Once you understand that NullPointerException occurs because of null object, by looking at stack trace of NullPointerException. Since most common cause of NullPointerException is that reference variable pointing to null instead of an valid Object reference. Let's see an example of NullPointerException in Java :

/**
 *
 * Java program to demonstrate When NullPointerException occurs and
 * How to fix NullPointerException in Java
 *
 * @author java67
 */

public class Hello {

    private static String name;
 
    public static void main(String args[]){
     
        if(name.equals("Java")){
            System.err.println("Welcome to Java");
        }
    }
}

Exception in thread "main" java.lang.NullPointerException
        at test.CollectionTest.main(CollectionTest.java:18)



Now by looking output and stack trace we know that error occurred at line 18, where we are comparing name member variable to String literal "Java" e.g. name.equals("Java"), Since name is not initialized anywhere in program and its an String Object, it contains default value null, which is causing this NullPointerException . To avoid this NullPointerException we can do two things

1) first do a null check e.g. name != null before calling any method on that
2) we can use the fact that equals method return false if we compare it will null e.g. if we write code like "java".equals(name) we will not get any NullPointerException, instead it will return false.

In this Java tutorial we learn What is NullPointerException in Java, When does NullPointerException occurs in Java and How to fix NPE in Java. In Summary try to avoid NullPointerException by making sure you follow the contract e.g. Using object when its initialized and by defensive coding. You can also write null safe method likes equals() if you don't trust your client to avoid NullPointerException in Java.

Other Java fundamental tutorials from java67

1 comment:

  1. Adding null in Java programming language is biggest mistake by Java designer, They should have provided better default value like empty and should not be allowed to fail application by programming language itself just like many scripting language e.g python or perl do.

    ReplyDelete

Java67 Headline Animator