Saturday, June 18, 2016

java.util.Optional, Tired of Null Pointer Exceptions, get rid of Null Pointer Exceptions, Handle NullPointerException in Java

See this below java code to add two Integer:

public Integer sumOfTwoInteger(Integer a, Integer b){
      return a + b;

Here, sumOfTwoInteger() method at all not taking care of any of the method arguments, this method will be executed either you pass any valid Integer value or any null value. Even, from where (caller method) you will call this sumOfTwoInteger() method, caller method will be also taking care for data is going to pass to sumOfTwoInteger() method. Finally ends up with this below error message:

Integer a = null;
Integer b = 10;


Exception in thread "main" java.lang.NullPointerException
at Tester.sumOfTwoInteger(
at Tester.main(

Now, how to handle this kind of situation where null check is to be check always and each and every place, before calling method or during method is being executed.

User java.util.Optional package.

import java.util.Optional;

public class Tester {
   public static void main(String args[]) {
      Tester guavaTester = new Tester();
      Integer invalidInput = null;
      Optional a =  Optional.of(invalidInput);
      Optional b =  Optional.of(new Integer(10));

   public Integer sumOfTwoInteger(Optional a, Optional b){
     return a.get() + b.get();


Now, when you will run this code, it will give error at line, where you are trying to create Integer value a.

Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Unknown Source)
at java.util.Optional.(Unknown Source)
at java.util.Optional.of(Unknown Source)
at Tester.main(

More details at

No comments:

Post a Comment

You can put your comments here (Either feedback or your Question related to blog)