[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



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


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 Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency