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.
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.