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!");
        }
    }
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!