[Fix] Java Exception with Lambda - Cannot invoke because object is null


Example:
import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<>();
        stringList.add("Java");
        stringList.add("Example");
        stringList.add("Text");
        stringList.add(null);

        stringList.forEach(str -> System.out.println(str.substring(1))); //error

    }
}

In the above example as you can see I am iterating through a ArrayList of Strings that have a null value as well, so when I use forEach loop over it and iterate and do a subString on the array elements, I will get an NPE (Null Pointer Exception)

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.substring(int)" because "str" is null
at Example.lambda$main$0(Example.java:14)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at Example.main(Example.java:14)


So as a developer you would need to handle the Unchecked NPE!

import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<>();
        stringList.add("Java");
        stringList.add("Example");
        stringList.add("Text");
        stringList.add(null);

       stringList.forEach(str -> {
           if(str == null) {
              System.out.println("NULL Value");
           } else {
               System.out.println(str.substring(1));
           }
       });

    }
}
Java 8 Exception - cannot invoke because object is null
Java 8 Exception - cannot invoke because the object is null
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap