NullPointerException in Java

One of the most common and nightmare for the Java programmers are getting the NullPointerException while running the Java application. This exception is defined at the “java.lang” package and the purpose of the exception is to detect if an object is used without any content. Here you must understand the difference between Reference and Object. A reference variable is just a handler which hold an actual object in a memory. In the below example:

Employee emp = new Manager();

In the above code, “emp” is reference of Employee class which holds the object of type “Manager”. Here you can assume that if the “emp” reference is not assigned to any of the object, then it will have empty reference or null value. Look at the below example:

package javabeat.net.core;

public class NullPointerExceptionExample {
	public static void main(String args[]){
		Employee emp = null;
		emp.method();
	}
}
abstract class Employee{
	public abstract void method();
}
class Manager extends Employee{
	public void method(){
		System.out.println("test method");
	}
}

If you run the above program, you will get the following exception:

Exception in thread "main" java.lang.NullPointerException
	at javabeat.net.core.NullPointerExceptionExample.main(NullPointerExceptionExample.java:6)

The above example is very much straight forward implementation to show the reason for the NullPointerException. However, in the real scenario it will be more complicated to detect the object reference if its null. The only way to avoid the situation is to do the good practice of checking null values before accessing any values. Look at the same example below:

package javabeat.net.core;

public class NullPointerExceptionExample {
	public static void main(String args[]) {
		Employee emp = null;
		if (emp != null) {
			emp.method();
		} else {
			emp = new Manager();
			emp.method();
		}
	}
}

abstract class Employee {
	public abstract void method();
}

class Manager extends Employee {
	public void method() {
		System.out.println("test method");
	}
}

I have added the “if” condition to check if the “emp” reference is pointing to the null, if so I am creating the object and then calling it. Like this you can take the manual handling to avoid the NullPointerException in your application.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*