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:
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!");
}
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!