Monday, 16 June 2014

Avoid NullPointerException in Java Applications

Hi Guys!!! Hope you all doing well.
Today  we are going to discuss a very common type exception in java application. The name of this Exception is "Null Pointer Exception" . It is common exception face by developer.  So we can keep some point in mind during coding to handle this exception.
At first what  is "Null Pointer Exception"?
NullPointerException is an unchecked exception and extends RuntimeException. It doesn’t force you to use catch block to handle it. So NullPointerException is a RuntimeException. NullPointerException is thrown when an application attempts to use an object reference, having the null value.
   Here some common cause of NullPointerException in Java .

  1. Calling toString() method on object which is null
  2. Comparing object properties in if block without checking null equality
  3. Calling the instance method of a null object.
  4. Accessing or modifying the field of a null object.
  5. Taking the length of null as if it were an array.
  6. Accessing or modifying the slots of null as if it were an array.
  7. Throwing null as if it were a Throwable value.

Now I am going to discuss best practices to avoid NullPointerException .
1.  Call equals() and equalsIgnoreCase() method on known String literal rather unknown object
Always call equals() method on known String which is not null. Since equals() method is symmetric, calling a.equals(b) is same as calling b.equals(a), and that’s why many programmer don’t pay attention on object a and b. One side effect of this call can result in NullPointerException, if caller is null.
Object unknownObject = null;

//wrong way - may cause NullPointerException
if(unknownObject.equals("knownObject")){
   System.err.println("This may result in NullPointerException if unknownObject is null");
}

//right way - avoid NullPointerException even if unknownObject is null
if("knownObject".equals(unknownObject)){
    System.err.println("better coding avoided NullPointerException");
}
This is the most easy Java tip or best practice to avoid NullPointerException, but results in tremendous improvement, because of equals()being a common method.
2.  Prefer valueOf() over toString() where both return same result
Since calling toString() on null object throws NullPointerException, if we can get same value by calling valueOf() then prefer that, as passing null to  valueOf() returns "null", specially in case of wrapper classes  like Integer, Float, Double or BigDecimal.
BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //doesn’t throw NPE
System.out.println(bd.toString()); //throws "Exception in thread "main" java.lang.NullPointerException"
3) Using null safe methods and libraries
There are lot of open source library out there, which does the heavy lifting of checking null for you. One of the most common one is StringUtils from Apache commons. You can use StringUtils.isBlank(), isNumeric(), isWhiteSpace() and other utility methods without worrying of  NullPointerException.
//StringUtils methods are null safe, they don't throw NullPointerException
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isNumeric(null));
System.out.println(StringUtils.isAllUpperCase(null));

Output:
true
true
false
false
5)  Use of annotation @NotNull and @Nullable
While writing method you can define contracts about nullability, by declaring whether a method is null safe or not, by using annotations like @NotNull and @Nullable. Modern days compiler, IDE or tool can read this annotation and assist you to put a missing null check, or may inform you about an unnecessary null check, which is cluttering your code. IntelliJ IDE and findbugs already supports such annotation. These annotations are also part of JSR 305, but even in the absence of any tool or IDE support, this  annotation itself work as documentation. By looking @NotNull and @Nullable, programmer can himself decide whether to check for null or not. By the way ,this is relatively new best practice for Java programmers and it will take some time to get adopted.
6)  Avoid unnecessary autoboxing and unboxing in your code
Despite of other disadvantages like creating temporary object, autoboxing are also prone to NullPointerException, if the wrapper class object is null. For example,  following code will fail with NullPointerException if person doesn't have phone number and instead return null.
Person ram = new Person("ram");
int phone = ram.getPhone();
Not just equality but < , > can also throw NullPointerException if used along autoboxing and unboxing. See this article to learn more pitfalls of autoboxing and unboxing in Java.

This is some sort of technic you can use to reduce Null Pointer exception in your code. You can explore more on it . If you really care for this.
 Happy Coding !!!

1 comment:

  1. Very useful information that you have shared and it is very useful to me.Thanks for sharing the information with us.

    ios app development company in chennai

    ReplyDelete

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...