value)f()

Showing posts with label value)f(). Show all posts
Showing posts with label value)f(). Show all posts

How to avoid NullPointerException


java.lang.NullPointerException

When can it be thrown?

According to the JavaDoc, the following scenarios can be found.
  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

How to avoid it?

  • Use Optional in Java 8
  • Call equals() and equalsIgnoreCase() methods on known objects.
  • Use valueOf() over toString()
public class NullCheckDemo {
   public static void main(String args[]){
       Integer i = null;
       System.out.println(i.toString());      //This throws NullPointerException
       System.out.println(String.valueOf(i)); //This returns null
   }
}
  • Use null-safe methods and libraries. Ex: Apache Commons StringUtils.
  • Use @NotNull and @Nullable annotations
  • Always check for nulls.
public class NullDemo {
    public static void main(String args[]){
        Integer i = null;

        if(i != null)
            System.out.println(i);
        else
            System.out.println("error occurred");
    }
}