Total Pageviews

Sunday, February 15, 2015

How to avoid NullPointerExceptions.

NullPointerExceptions -

  1. Call equals() and equalsIgnoreCase() method on known String literal rather unknown object -
    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");
    }

  2. Prefer valueOf() over toString() where both return same result
    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 -
    //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

  4. Avoid returning null from method, instead return empty collection or empty array (This Java best practice or tips is also mentioned by Joshua Bloch in his book Effective Java) -
    public List getOrders(Customer customer){
       List result = Collections.EMPTY_LIST;
       return result;
    }

--

Thanks & Regards
Manish Kumar





No comments:

Post a Comment