Best ways to avoid NullPointerException
1) Ternary Operator
This operator results to the value on the left hand side if not null else right hand side is evaluated. It has syntax like :
boolean expression ? value1 : value2;
If expression is evaluated as true then entire expression returns value1 otherwise value2. Its more like if-else construct but it is more effective and expressive. To prevent NullPointerException (NPE) , use this operator like below code:
String str = (param == null) ? "NA" : param;
2) Use apache commons StringUtils for String operations
Apache commons lang is a collection of several utility classes for various king of operation. One of them is StringUtils.java. Use StringUtils.isNotEmpty() for verifying if string passed as parameter is null or empty string. If it is not null or empty; then use it further.
Other similar methods are StringUtils. IsEmpty(), and StringUtils.equals(). They claim in their javadocs that if
StringUtils.isNotBlank() throws an NPE, then there is a bug in the API.
if (StringUtils.isNotEmpty(obj.getvalue())){
String s = obj.getvalue();
....
}
3) Check Method Arguments for null very early
You should always put input validation at the beginning of your method so that the rest of your code does not have to deal with the possibility of incorrect input. So if someone passes in a null, things will break early in the stack rather than in some deeper location where the root problem will be rather difficult to identify.
Aiming for fail fast behavior is a good choice in most situations.
4) Consider Primitives Rather than Objects
Null problem occurs where object references points to nothing. So it is always safe to use primitives as much as possible because they does not suffer with null references. All primitives must have some default values also attached so beware of it.
5) Carefully Consider Chained Method Calls
While chained statements are nice to look at in the code, they are not NPE friendly. A single statement spread over several lines will give you the line number of the first line in the stack trace regardless of where it occurs.
ref.method1().method2().method3().methods4();
These kind of chained statement will print only “NullPointerException occurred in line number xyz”. It really is hard to debug such code. Avoid such calls.
6) Use String.valueOf() Rather than toString()
If you have to print the string representation of any object, the don’t use object.toString(). This is a very soft target for NPE. Instead use String.valueOf(object).
Even if object is null in second method, it will not give exception and will prints ‘null’ to output stream.
7) Avoid returning null from your methods
An awesome tip to avoid NPE is to return empty strings or empty collections rather than a null. Do this consistently across your application. You will note that a bucket load of null checks become unneeded if you do so.
An example could be:
List<string> data = null;
@SuppressWarnings("unchecked")
public List getDataDemo()
{
if(data == null)
return Collections.EMPTY_LIST; //Returns unmodifiable list
return data;
}
Users of above method, even if they missed the null check, will not see ugly NPE.
8) Discourage Passing of Null Parameters
I have seen some method declarations where method expects two or more parameters. If one of parameter is passed as null, then also method works if some different manner. Avoid this.
In stead you should define two methods; one with single parameter and second with two parameters. Make parameters passing mandatory. This helps a lot when writing application logic inside methods because you are sure that method parameters will not be null; so you don’t put unnecessary assumptions and assertions.
9) Call String.equals(String) on ‘Safe’ Non-Null String
In stead of writing below code for string comparison
public class SampleNPE {
public void demoEqualData(String param) {
if (param.equals("check me")) {
// some code
}
}
}
write above code like this. This will not cause in NPE even if param is passed as null.
public class SampleNPE {
public void demoEqualData(String param) {
if ("check me".equals(param)) // Do like this
{
// some code
}
}
}
Reference http://howtodoinjava.com/2013/04/05/how-to-effectively-handle-nullpointerexception-in-java/