Saturday 12 March 2016

WHY NullPointerException occur and How to Handle NullPointerException in Java

How to Effectively Handle NullPointerException in Java


ans:-NullPointerException is an unchecked exception and extends RuntimeException.
      It doesn’t force you to use catch block to handle it

Q-Why NullPointerException occur in your code?
ans-"NullPointerException is a situation in code where you try to access/ modify an object which has not been initialized yet"
means that object reference variable is not pointing anywhere and refers to nothing or ‘null’.
 A simple example can be:
package com.piyush.npe;
public class SampleNPE {
    public static void main(String[] args) {
        String s = null;
        System.out.println(s.toString()); // s is un-initialized and is null
    }
}



Note:-Common places where NullPointerException usually occur

ans:-NullPointerException can occur anywhere in your code
1:-) Invoking methods on an object which is not initialized.
2:-) Incorrect configuration for frameworks like spring which works on dependency injection
3:-) Parameters passed in a method are null.
4:-) Calling toString() method on object which is null.
5:-) Using synchronized on an object which is null
6:-) Chained statements i.e. multiple method calls in a single statement.
7:-) Comparing object properties in if block without checking null equality.

Q-How to avoid the NullPointerException?

ans:-First ensure that all your objects are initialized properly.
note:-If you are dealing with static variables or static method than you won’t get null pointer exception
Check Each Object For Null Before Using

I listed how to avoid NPE:-
1- Empty Collection
2- Use some Methods
3- assert Keyword
4- Assert Class
5- Exception Handling
6- Too many dot syntax
7- StringUtils Class


1:-) Prefer String.valueOf() method instead of toString().
example:-
package com.piyush.npe;
public class SampleNPE {
    public static void main(String[] args) {
        String s = null;
        System.out.println(String.valueOf(s)); // using String.valueOf(s) we can avoid nullpointerException;
    }
}


2:-) Use annotations @NotNull and @Nullable.

3:-) Empty Collection
Empty collection is collection which hasn’t any elements. Some developers return null value for Collection which has no elements but this is false, you should return Collections.EMPTY_LIST, Collections.EMPTY_SET andCollections.EMPTY_MAP.
example:-
public static List getEmployees() { 
2  List list = Collections.EMPTY_LIST; 
3  return list; 
4

4:-)Use some Method
Use some methods to assure that null value not exist like contains(), indexOf(), isEmpty(), containsKey(), containsValue() and hasNext().
example:-
public class Example {
02     private static List<Integer> numbers = null;
03
04     public static List<Integer> getList() {
05          if (numbers == null)
06               return Collections.emptyList();
07          else
08               return numbers;
09     }
10}
 example2:- 
     String myName = "Piyush Kumar  Bangalore"; 
     List list = Collections.EMPTY_LIST;  
     boolean exist = list.contains(myName);  
     int index = list.indexOf(myName);  
     boolean isEmpty =list.isEmpty();  
       
     Map map =Collections.EMPTY_MAP;  
     exist=map.containsKey(myName);  
     exist=map.containsValue(myName);  
     isEmpty=map.isEmpty();  
       
     Set set=Collections.EMPTY_SET;  
     exist=set.contains(myName);  
     isEmpty=set.isEmpty();  
       
     Iterator iterator;  
     exist = iterator.hasNext();

5:-)Exception Handling:-
example:-a- try catch statement
I will change calling code to below code
1String managerId = getManager("A015"); 
2try 
3  System.out.println(managerId.toString()); 
4catch (NullPointerException npe) { 
5  //write your code here 
6}
b- Checking of Null values
I will change calling code to below code
1String managerId = getManager("A015"); 
2if (managerId != null) { 
3  System.out.println(managerId.toString()); 
4else 
5  //write your code here 
6}
6:-) StringUtils Class
StringUtils class is part of org.apache.commons.lang package, I can use it to avoid NPE specially all its methods are null safe
For example StringUtils. IsEmpty(), StringUtils. IsBlank(), StringUtils.equals(), and much more.
examle:-You can make use of the StringUtils.isNotEmpty, StringUtils.IsEmpty and StringUtils.equals methods, in order to avoid the NullPointerException. For example:
1if (StringUtils.isNotEmpty(str)) {
2     System.out.println(str.toString());
3}

7:-)assert Keyword
8-:) Assert Class


second way:-

How to solve a NullPointerException in Java?

It is simple, put a null check! Surround your object with if statement like
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}



No comments:

Post a Comment