How to prevent obvious null pointer exceptions

July 21, 2010 - 3:12am
Submitted by gary

Just a simple note about bugs caused by null pointer exceptions when evaluating 2 values.
lets look at the following:
 
if (car.equals("Ford")) {
     return true;
}
 
if car is null, we will have a null pointer exception right here...
so if we do:
if ("Ford".equals(car)){
     return true;
}
 
then we wont have to check if car is null before comparing.
 
This is one of the most common null pointer codes I have seen by doing code reviews for years.