Lessening NullPointerException Occurance

Most of the time NullPointerException is hard to avoid but you can lessen its occurrence on your application. For example you are comparing a String object to a String literal

Don't do this


String lCountry = getCountry();
if(lCountry.equals("Philippines")){
//Do Something
}


Do this instead


String lCountry = getCountry();
if(("Philippines").equals(lCountry)){
//Do Something
}


The first implementation could lead to a null pointer exception if getCountry() returned null. Note that on both cases you are creating a String Object with value Philippines so doing it the other way around will avoid avoid NullPointerException.

There is another way to do this by using apache commons StringUtils.equals() which is null safe.


About this entry


0 comments: