Design a site like this with WordPress.com
Get started

Null Pointer Exception

Null Pointer Exception or NPE is one of the most common exception that anyone of us have encountered as a development engineer.

It is usually thrown when we try to access a method on a reference variable for which a value is evaluated to null.

for e.g

Employee e = getEmployee(123);
e.getEmployeeName();

The above code can throw a NPE. The above code assumes that the “getEmployee” method will always return a value but it may happen that it wont and return null;

In such a case the code at line 2 throws NPE as we are trying to access “getEmployeeName()” on a null value.

Mind you, the NPE is a runtime exception and the compiler will not complain that you have not handled a null check.

How to Resolve

In most cases a simple null check resolves the problem. Like in the above example an If condition will avoid NPE

Employee e = getEmployee(123);
if(e!=null)
e.getEmployeeName();

A code should be written to identify such conditions and handle them wherever necessary. As NPE is a runtime exception, if the code is not handled for null object access, the program might very well terminate abruptly for a small null check.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: