Monday, November 4, 2013

Can you spot a NPE (Null Pointer Exception)?

What is the most common exception that java developer are experiencing? The straight forward answer is NPE. Here I’m not going to discuss all the possibilities of NPE but one freak possibility of getting NPE, you may miss while debugging the code.

Did you spot the NPE possibility ?

This code seems to be fine, there are null checks, no chance of getting NPE at for each loop ( it throws NPE if the list is null ). So where is the NPE possible loophole? Value of get(0) may be null. List is not like other collections, it can contain null values. So two things to remember.
  1. Do a null check before call trim method whenever there is a chance of getting null values as a String.
  2. List is a sequence of objects so there is no limitation of having null as an element of the list, Set also can contain at most one null element. So beware of such hidden null values.