Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 21
Question ID: UKOCP45182
Given code:
- package com.udayankhattry.ocp;
- import java.util.function.BiFunction;
- import java.util.function.BiPredicate;
- public class Test {
- public static void main(String[] args) {
- BiFunction<String, String, String> func = (str1, str2) -> {
- return (str1 + str2);
- };
- BiPredicate<String, String> predicate = (str1, str2) -> {
- return func.apply(str1, str2).length() > 10;
- };
- String [] arr = {"vention", "historic", "sident", "sentation", "vious"};
- for(String str : arr) {
- if(predicate.test("pre", str)) {
- System.out.println(func.apply("pre", str));
- }
- }
- }
- }
What is the result?
-
A
prevention
prehistoric
president
presentation
previous
-
B
prevention
prehistoric
president
presentation
-
C
prevention
prehistoric
presentation
-
D
prehistoric
presentation
- E presentation
- F Program terminates successfully without printing anything on to the console
Reveal correct answer
Correct answer: D
Explanation
UKOCP45182:
BiFunction<T, U, R> : R apply(T t, U u);
BiFunction interface accepts 3 type parameters, first 2 parameters (T,U) are passed to apply method and 3rd type parameter is the return type of apply method.
In this case, 'BiFunction<String, String, String>' means apply method will have declaration: String apply(String str1, String str2). Given lambda expression (str1, str2) -> { return (str1 + str2); }; is the correct implementation of BiFunction<String, String, String> interface. It simply concatenates the passed strings.
BiPredicate<T, U> : boolean test(T t, U u);
BiPredicate interface accepts 2 type parameters and these parameters (T,U) are passed to test method, which returns primitive boolean.
In this case, 'BiPredicate<String, String>' means test method will have declaration: boolean test(String s1, String s2). Given lambada expression (str1, str2) -> { return func.apply(str1, str2).length() > 10; }; is correct implementation of BiPredicate<String, String>. Also note, lambda expression for BiPredicate uses BiFunction. This predicate returns true if combined length of passed strings is greater than 10.
For-each loop simply iterates over the String array elements and prints the string after pre-pending it with "pre" in case the combined length of result string is greater than 10. "prehistoric" has 11 characters and "presentation" has 12 characters and hence these are displayed in the output.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
