java.lang.NullPointerException exception in JAVA

java.lang.NullPointerException in JAVA

Null pointer exception is an exception thrown when you try to access an object that does not have a value it means that is has never been instanciated using the new keyword.

public class NullPointerException {

    public static void main(String args[]) {
        String str = null;

        // This line will throw java.lang.NullPointerException
        str.toString();

        //fixing case 1: Test its nullability
        if(str!=null){
            str.toString();
        }

        //fixing case 2: Instanciate the variable
        str = new String("yami code");
        str.toString();
    }

}