How to handle java lang NullPointerException

NullPointerException is a type of Runtime exception, which is an unchecked exception in java. A null value can be assigned to an object reference. It is thrown when an application attempts to use null in a case where an object is required.

In this tutorial, we will see cases where the null pointer occurred and how to avoid or handle NullPointerException using the best approaches.

Cases when the null pointer exception can occur:

  • Call the instance method of a null object.
  • Getting or modifying the field of a null object.
  • call length method on the null array.
  • Getting or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Common cases where null always occurred

1). Comparing the null String to other String.

It is the most commonly occurred null pointer exception case. we getting string value from other methods or variables which value is null. When we go to compare those values. we will get a null pointer exception.

public class NullPointerExample1 { public static void main(String[] args) { String str = null; try { if (str.equals("hello")) { System.out.print("the strings are equlas"); } else { System.out.print("the strings are equlas"); } } catch(NullPointerException e) { System.out.print("NullPointerException occured while comaring the strings.." + e.getMessage()); } } } output: NullPointerException occured while comaring the strings..null

2). use the length method on a null array

Another common reason where we apply the length method on the null array which results in NPE.

package com.javacodestuffs.core.exceptions; public class NullPointerExample2 { public static void main(String[] args) { String str[] = null; System.out.print(str.length); } } output: Exception in thread "main" java.lang.NullPointerException at com.javacodestuffs.core.exceptions.NullPointerExample2.main(NullPointerExample2.java:6)

Best ways to avoid Java NullPointerException

1). Use of Ternary Operator

The ternary operator can be used to avoid NullPointerException. In ternary operator, the boolean condition is evaluated, If the expression is true then, the value1 is returned, otherwise, the value2 is returned.

if(str == null) ? value1 : value2;

package com.javacodestuffs.core.exceptions; public class NullPointerExample3 { public static void main(String[] args) { String str = null; String message = (str == null) ? "String is null.": "String is not null."; System.out.println(message); } } output: String is null.

2). Keep a check on the arguments of a method

We can avoid the null pointer exception before executing the method body. For that, we have to do 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. If the null value detected, we can handle it with appropriate messages.

3). Calling equals on literal rather than the object.

package com.javacodestuffs.core.exceptions; public class NullPointerExample4 { public static void main(String[] args) { String str[] = null; try { if ("hello".equals(null)) { System.out.print("the strings are equals."); } else { System.out.print("the strings are not equals."); } } catch(NullPointerException e) { System.out.print("NullPointerException occured while comaring the strings.." + e.getMessage()); } } } output: the strings are not equals.

4). Use the String.valueOf() Rather than toString()

If you want string representation of any object, the don't use object.toString(). This is the main cause for NPE. Instead use String.valueOf(object).

Even if the object is null, it will not throw an exception and will prints 'null' to the console.

package com.javacodestuffs.core.exceptions; public class NullPointerExample5 { public static void main(String[] args) { StringBuilder sb = null; System.out.print("The value of string is : " + sb.toString()); } } output: Exception in thread "main" java.lang.NullPointerException at NullPointerExample5.main(NullPointerExample5.java:6)

package com.javacodestuffs.core.exceptions; public class NullPointerExample5 { public static void main(String[] args) { StringBuilder sb = null; System.out.print("The value of string is : " + String.valueOf(sb)); } } output: The value of string is : null

5). Avoid returning null from your methods

This is another good approach to avoid NPE. While returning from the method, return empty strings or empty collections rather than a null.

List strlist = null; public List getDataDemo() { if(strlist == null) return Collections.EMPTY_LIST; //Returns unmodifiable list return strlist; }

6). Initialize collection with Empty type instead of null

List list = Collections.EMPTY_LIST; Set set = Collections.EMPTY_SET; Map map = Collections.EMPTY_MAP; List s = Collections.emptyList(); Set l = Collections.emptySet(); Map d = Collections.emptyMap();

Post/Questions related to   How to handle java.lang.NullPointerException

Can we catch Nullpointerexception in Java?
How to handle null pointer exception in java?
Yes
How do you handle the null exception in Java?

In this article, we have seen How to handle  java.lang.NullPointerException with examples. All source code in the article can be found in the GitHub repository.