[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
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.