Java NullPointerException

Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException. NullPointerException doesn’t force us to use a try-catch block to handle it.

NullPointerException has been very much a nightmare for most Java developers. It usually pop up when we least expect them.

I have also spent a lot of time while looking for reasons and the best approaches to handle null issues. I will be writing here some of the best practices followed industry-wise, sharing some expert talks and my own learning over time.

1. Why NullPointerException Occur in the Code?

NullPointerException is a runtime condition where we try to access or modify an object which has not been initialized yet. It essentially means that the object’s reference variable is not pointing anywhere and refers to nothing or ‘null’.

In the given example, String s has been declared but not initialized. When we try to access it in the next statement s.toString(), we get the NullPointerException.

package com.howtodoinjava.demo.npe;

public class SampleNPE
{
   public static void main(String[] args)
   {
      String s = null;
      System.out.println( s.toString() );   // 's' is un-initialized and is null
   }
}

2. Common Places Where NPEs Occur?

Well, NullPointerException can occur anywhere in the code for various reasons but I have prepared a list of the most frequent places based on my experience.

  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

This is not an exhaustive list. There are several other places and reasons also. If you can recall any such other, please leave a comment. it will help others also.

3. Best Ways to Avoid NullPointerException

3.1. Use Ternary Operator

Ternary operator results in 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 the expression is evaluated as true then the entire expression returns value1 otherwise value2.

It is more like an if-else construct but it is more effective and expressive. To prevent NullPointerException (NPE), use this operator like the below code:

String str = (param == null) ? "NA" : param;

3.2. Use Apache Commons StringUtils for String Operations

Apache Commons Lang is a collection of several utility classes for various kinds of operation. One of them is StringUtils.java.

Use the following methods for better handling the strings in your code.

  • StringUtils.isNotEmpty()
  • StringUtils. IsEmpty()
  • StringUtils.equals()
if (StringUtils.isNotEmpty(obj.getvalue())){
    String s = obj.getvalue();
    ....
}

3.3. Fail Fast Method Arguments

We should always do the method input validation at the beginning of the method so that the rest of the code does not have to deal with the possibility of incorrect input.

Therefore if someone passes in a null as the method argument, things will break early in the execution lifecycle 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.

3.4. Consider Primitives instead of Objects

A null problem occurs where object references point to nothing. So it is always safe to use primitives. Consider using primitives as necessary because they do not suffer from null references.

All primitives have some default value assigned to them so be careful.

3.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 if possible.

3.6. Use valueOf() in place of toString()

If we have to print the string representation of any object, then consider not using toString() method. This is a very soft target for NPE.

Instead use String.valueOf(object). Even if the object is null in this case, it will not give an exception and will print ‘null‘ to the output stream.

3.7. Avoid Returning null from Methods

An awesome tip to avoid NPE is to return empty strings or empty collections rather than null. Java 8 Optionals are a great alternative here.

Do this consistently across your application. You will note that a bucket load of null checks becomes unneeded if you do so.

List<string> data = null;
 
@SuppressWarnings("unchecked")
public List getDataDemo()
{
   if(data == null)
      return Collections.EMPTY_LIST; //Returns unmodifiable list
   return data;
}

Users of the above method, even if they missed the null check, will not see the ugly NPE.

3.8. Discourage Passing of null as Method Arguments

I have seen some method declarations where the method expects two or more parameters. If one parameter is passed as null, then also method works in a different manner. Avoid this.

Instead, we should define two methods; one with a single parameter and the 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.

3.9. Call equals() on ‘Safe’ Non-null Stringd

Instead of writing the below code for string comparison

if (param.equals("check me")) {
 // some code
}

write the above code like given below example. This will not cause in NPE even if param is passed as null.

if ("check me".equals(param)) {
 // some code
}

4. NullPointerException Safe Operations

4.1. instanceof Operator

The instanceof operator is NPE safe. So, instanceof null always returns false.

This operator does not cause a NullPointerException. You can eliminate messy conditional code if you remember this fact.

// Unnecessary code
if (data != null &amp;&amp; data instanceof InterestingData) {
}
 
// Less code. Better!!
if (data instanceof InterestingData) {
}

4.2. Accessing static Members of a Class

If you are dealing with static variables or static methods then you won’t get a null pointer exception even if you have your reference variable pointing to null because static variables and method calls are bonded during compile time based on the class name and not associated with the object.

MyObject obj = null;
String attrib = obj.staticAttribute; 

//no NullPointerException because staticAttribute is static variable defined in class MyObject

Please let me know if you know some more such language constructs which do not fail when null is encountered.

5. What if we must allow NullPointerException in Some Places

Joshua bloch in effective java says that “Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.”

So if you must allow NullPointerException in some places in your code then make sure you make them more informative than they usually are.

Take a look at the below example:

package com.howtodoinjava.demo.npe;
 
public class SampleNPE {
   public static void main(String[] args) {
      // call one method at a time
      doSomething(null);
      doSomethingElse(null);
   }
 
   private static String doSomething(final String param) {
      System.out.println(param.toString());
      return "I am done !!";
   }
 
   private static String doSomethingElse(final String param) {
      if (param == null) {
         throw new NullPointerException(
               " :: Parameter 'param' was null inside method 'doSomething'.");
      }
      System.out.println(param.toString());
      return "I am done !!";
   }
}

Output of both method calls is this:

Exception in thread "main" java.lang.NullPointerException
 at com.howtodoinjava.demo.npe.SampleNPE.doSomething(SampleNPE.java:14)
 at com.howtodoinjava.demo.npe.SampleNPE.main(SampleNPE.java:8)
 
Exception in thread "main" java.lang.NullPointerException:  :: Parameter 'param' was null inside method 'doSomething'.
 at com.howtodoinjava.demo.npe.SampleNPE.doSomethingElse(SampleNPE.java:21)
 at com.howtodoinjava.demo.npe.SampleNPE.main(SampleNPE.java:8)

Clearly, the second stack trace is more informative and makes debugging easy. Use this in the future.

I am done with my experience around NullPointerException. If you know other points around the topic, please share with all of us !!

Happy Learning !!

Comments

Subscribe
Notify of
guest
19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode