Handling NullPointerException with Java Predicate


Let's take an example where the String we are working with is null.

Example:
package org.code2care.examples;

import java.util.function.Predicate;

public class PredicateAndExample {

    public static void main(String... args) {

        Predicate<String> startsWithU = text -> text.startsWith("U");
        String str = null;
        boolean result = startsWithU.test(str);
        System.out.println("String starts with U? " + result);

    }
}
Output:

Exception in thread "main" java.lang.NullPointerException:
          Cannot invoke "String.startsWith(String)" because "text" is null
             at org.code2care.examples.PredicateAndExample.lambda$main$0(PredicateAndExample.java:8)
             at org.code2care.examples.PredicateAndExample.main(PredicateAndExample.java:10)



As NullPointerException is a Runtime Exception, we can handle it using a null check and maybe a logic that works based on your use-case.

package org.code2care.examples;

import java.util.function.Predicate;

public class PredicateAndExample {

    public static void main(String... args) {
        Predicate<String> startsWithU = text -> text != null && text.startsWith("U");
        String str = null;

        if (str != null) {
            boolean result = startsWithU.test(str);
            System.out.println("String starts with U? " + result);
        } else {
            System.out.println("String is null!");
        }
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap