JavaRush /Java Blog /Random EN /Tips and advice. How to Avoid NullPointerException in Jav...
DarthVictor
Level 28

Tips and advice. How to Avoid NullPointerException in Java Applications

Published in the Random EN group
Tips and advice.  How to Avoid NullPointerException in Java Applications - 1Today 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. Tips and advice.  How to Avoid NullPointerException in Java Applications - 2

Call the equals() and equalsIgnoreCase() methods on a known literal string, not on an unknown object

Always call a method equals()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 anot ), and for this reason b, nullmany programmers do not pay attention to which objects are called equals(), y aor 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 calling toString()on a reference with a value nullthrows a NullPointerException, it's better to use a call valueOf()when we can get the same result, since calling valueOf()from nullreturns null. This is especially true for wrapper classes such as Integer, Float, Doubleor 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 nullor 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 StringUtilsfrom 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 nullfor -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 nullfrom 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: CollectionsCollections.EMPTY_LISTCollections.EMPTY_SETCollections.EMPTY_MAP
public List getOrders(Customer customer){
   List result = Collections.EMPTY_LIST;
   return result;
}
Similarly, you can use Collections.EMPTY_SETand Collections.EMPTY_MAPinstead of returning null.

Use the @NotNull and @Nullable annotations

In your method declarations, you can define the nullmethod's -safety convention, using annotations @NotNulland @Nullable to indicate whether a method can return nullor 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 @NotNulland @Nullableit will be easier for the programmer to understand where to add a check fornulland 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 is null. 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 object Employeecannot be created without a name and id, but may not have a phone number. In this case, for objects Employeedevoid of a number, instead ofnullmay return zero. Although this behavior of the object should be thought out in advance - it may be easier to check for nullthan to call a non-existent number. In this case, having additional conditions on which fields are nulland which are not will help you make the right decision. In general, the choice between crashing a program immediately or taking it over nullis 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 " " != nullfrom the program code.

Use the Null Object Pattern

Creating special Null-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 Iteratorthat is used to iterate through the collection. Then if the original object doesn't have any iterator, instead nullyou 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
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION