27 April, 2012

Avoid Null Pointer Exception Part 1


Null Pointer Exception is the most common and most annoying exception in Java.
In this post I want to avoid this undesired exception.

First let's create example that raise Null Pointer Exception
   private Boolean isFinished(String status) {  
     if (status.equalsIgnoreCase("Finish")) {  
       return Boolean.TRUE;  
     } else {  
       return Boolean.FALSE;  
     }  
   }  

In previous method if we pass the value of "status" variable as null it will raise Null Pointer Exception in below line
if (status.equalsIgnoreCase("Finish")) {



So we should change my code to below code to avoid Null Pointer Exception
    private Boolean isFinished(String status) {
        if ("Finish".equalsIgnoreCase(status)) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

In previous method if we path the value of "status" variable as null it will not raise Null Pointer Exception.

Conclusion
If you have object.equals(”literal”) you should replace with “literal”.equals(object) .

If you have object.equals(Enum.enumElement) you should replace with Enum.enumElement.equals(object).

At general expose equals method of the object that you are sure that it doesn't has null value.

Thanks
Recommended Post Slide Out For Blogger