NullPointerException is an unchecked exception & extends RuntimeException.
1) Invoking methods on an object which is not initialized
2) Parameters passed in a method are null
3) Calling toString() method on object which is null
4) Comparing object properties in if block without checking null equality
5) Incorrect configuration for frameworks like spring which works on dependency injection
6) Using synchronized on an object which is null
7) Chained statements i.e. multiple method calls in a single statement
To avoid this exception by using following ways:
1) String comparison with literals
ex: String str=null;
if("test".equals(str)){
}
//use this instead of
if(str.equals("Test")){
}
2) Check the argus of method
void method(String s){
if(s==null) throws exception
3) Prefer String.valueOf() method instead of toString()
4) Use Ternary operator
5) Create methods that return empty collections instead of null
6) If your application code makes use of collections then use Use the contains(), containsKey(), containsValue() methods
7) Use Assertions
public static int getLength(String s) {
assert (s != null);
return s.length();
}
8) Check the return value of external methods
And in the last don't forget to do the unit test.
(Not my creation found it on the net)