Today I will show you simple tricks on how to avoid NullPointerException in your applications. They are easy to follow, but they greatly improve the reliability and quality of your code. Moreover, in my experience, one first tip will have a noticeable impact on the quality of your code. If you know any other Java programming tricks, feel free to share them in the comments.
Use
There are many open source libraries that take the heavy burden of checking for Try not to return
This is another good Java programming tip that Joshua Bloch describes in his book "Java. Programming Effectively". When returning empty collections or arrays, make sure that no NullPointerException is thrown when calling base methods like
Call the equals() and equalsIgnoreCase() methods on a known literal string, not on an unknown object
Always call a methodequals()
on a known string that you know is not a null
. The method equals()
is symmetrical, that is, calling a.equals(b)
and b.equals(a)
will give the same result (if a
not ), and for this reason b
, null
many programmers do not pay attention to which objects are called equals()
, y a
or y b
. One of the side effects of this is a NullPointerException if the method is called on null
.
Object unknownObject = null;
//плохой способ - может вызвать NullPointerException
if(unknownObject.equals("knownObject")){
System.err.println("This may result in NullPointerException if unknownObject is null");
}
//правильный способ - исключение NullPointerException не возникнет, даже если unknownObject null
if("knownObject".equals(unknownObject)){
System.err.println("better coding avoided NullPointerException");
}
This was the easiest tip to avoid NullPointerException, but it alone leads to huge improvements since the method equals()
is ubiquitous.
Choose valueOf() over toString() in cases where both produce the same result
Because callingtoString()
on a reference with a value null
throws a NullPointerException, it's better to use a call valueOf()
when we can get the same result, since calling valueOf()
from null
returns null
. This is especially true for wrapper classes such as Integer
, Float
, Double
or BigDecimal
.
BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //не выбрасывает NPE
System.out.println(bd.toString()); //выбрасывает "Exception in thread "main" java.lang.NullPointerException"
Use these tips when you're not sure if an object can be null
or not.
Use null
-safe methods and libraries
There are many open source libraries that take the heavy burden of checking for null
. One of the most common is StringUtils
from Apache Commons. Using methods like StringUtils.isBlank()
, isNumeric()
, isWhiteSpace()
etc. you don't have to worry about NullPointerException being thrown.
//Методы StringUtils являются null-безопасными, они не вызовут 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 Be sure to read the documentation null
for -safe methods and classes before using it. This is another one of the best Java tricks that, without requiring much effort, leads to huge improvements.
Try not to return null
from a method, return an empty collection instead
This is another good Java programming tip that Joshua Bloch describes in his book "Java. Programming Effectively". When returning empty collections or arrays, make sure that no NullPointerException is thrown when calling base methods like size()
or . Convenient implementations of empty lists, sets and dictionaries are specially declared length()
in the class : , and . For example: Collections
Collections.EMPTY_LIST
Collections.EMPTY_SET
Collections.EMPTY_MAP
public List getOrders(Customer customer){
List result = Collections.EMPTY_LIST;
return result;
}
Similarly, you can use Collections.EMPTY_SET
and Collections.EMPTY_MAP
instead of returning null
.
Use the @NotNull and @Nullable annotations
In your method declarations, you can define thenull
method's -safety convention, using annotations @NotNull
and @Nullable to indicate whether a method can return null
or not. Modern compilers and IDEs can use these annotations to analyze your code and issue appropriate advice, for example, about a missing check for null
, or vice versa, about the possibility of removing an extra check that clogs the code. Such annotations, for example, are supported by the IntelliJ IDE and FindBugs, and are included in JSR 305. But even if your IDE doesn't support such annotations, they are good documentation on their own. Looking at @NotNull
and @Nullable
it will be easier for the programmer to understand where to add a check fornull
and where not. This, by the way, is a fairly new practice among Java programmers, and it will take time for it to spread.
Avoid unnecessary autoboxing and autoboxing in your code
Not only does this lead to the creation of extra temporary objects, autoboxing can also throw a NullPointerException if the wrapper class isnull
. For example, the following code will throw a NullPointerException if the person record does not contain a phone number and returns null
.
Person ram = new Person("ram");
int phone = ram.getPhone();
When using autoboxing or autoboxing, not only equalities, but also inequalities <
, > >
can result in a NullPointerException.
Follow conventions and define reasonable defaults.
One of the best ways to avoid NullPointerException in Java is to properly declare coding conventions and follow them. Most NullPointerException exceptions occur when an object is attempted to be created without all the data and dependencies it needs. By disallowing the creation of incomplete objects, gracefully rejecting such requests, you will save yourself a large number of NullPointerExceptions in the future. Likewise, if you allow object creation, then you should choose a reasonable default value. For example, a class objectEmployee
cannot be created without a name and id
, but may not have a phone number. In this case, for objects Employee
devoid of a number, instead ofnull
may return zero. Although this behavior of the object should be thought out in advance - it may be easier to check for null
than to call a non-existent number. In this case, having additional conditions on which fields are null
and which are not will help you make the right decision. In general, the choice between crashing a program immediately or taking it over null
is an important design decision, and once you make a choice, you should follow it consistently.
Set limits at the DBMS level
When using a database to store your program's objects, such as Customers or Orders, it's a good idea to "null
-own" your objects at the DBMS level, with appropriate table constraints. Databases often contain information from multiple sources, and introducing missing value checks will increase the integrity of your data. In addition, the presence of checks for null at the DBMS level will reduce them in your Java code: by loading data from the database into Java objects, you can be sure of their presence and remove extra " " != null
from the program code.
Use the Null Object Pattern
Creating specialNull
-objects is another way to avoid NullPointerExcpetion in Java. Suppose some method in our application returns an object, which the program subsequently works with by calling its methods. For example, the method Collection.iterator()
returns an object of the class Iterator
that is used to iterate through the collection. Then if the original object doesn't have any iterator, instead null
you can return a special Null
-object that has a method that hasNext()
always returnsfalse
. That's it, dear reader, and that concludes my advice on getting Java programs rid of NullPointerException errors. You will appreciate how useful these simple and not burdensome rules can be. As a reminder, if you want to share some more NullPointerException tricks in Java programs, feel free to do so in the comments. Translated specifically for CodeGym students. Original
GO TO FULL VERSION