Null-pointer exceptions (null pointer Exception) are the most commonly encountered and most annoying exceptions. This article describes how to avoid null pointer exceptions.
First we look at the following example
Private Boolean isfinished (String status) {
if (status.equalsignorecase ("Finish")) {return
boolean.true;
} else {return
boolean.false;
}
}
If the value of status is empty, a null pointer exception appears (line 2nd of this example). So we should use the following methods
Private Boolean isfinished (String status) {
if ("Finish". Equalsignorecase (status)) {return
boolean.true;
} else {return
boolean.false;
}
}
In this case, the null pointer exception will not appear if the status is empty. I believe most of our friends already know this method, and if an object may be null, then you do not need to call its method directly.
Next I will provide several suggestions to avoid null pointers.
1. Judge whether the collection is empty.
2. Use some methods of judgment.
3.assert keywords.
4.Assert class.
5. Exception handling.
6. Too many points. Operation syntax.
7. Using the StringUtils class
1. Judge whether the collection is empty
Collection is null to mean that there are no elements in the Collection. Some developers often return NULL if they run into collection without elements, and better yet, you should return collections.empty_list,collections.empty_ Set or Collections.empty_map.
The wrong code
public static List GetEmployees () {
list list = null;
return list;
}
The right Code
public static List GetEmployees () {
list list = Collections.empty_list;
return list;
}