nerdexam
Oracle

1Z0-809 · Question #207

Given: `` public interface LengthValidator { public boolean checkLength(String str); } ` and ` public class Txt { public static void main(String[] args) { boolean res = new LengthValidator() {…

The correct answer is C. Supplier. There is an error in this question: the marked correct answer (C, Supplier) is actually wrong. The correct answer is B. Predicate. Here's the accurate explanation: Why B (Predicate) is correct: LengthValidator.checkLength takes a String and returns a boolean - which is exactly…

Question

Given:
public interface LengthValidator {
 public boolean checkLength(String str);
}
and
public class Txt {
 public static void main(String[] args) {
 boolean res = new LengthValidator() {
 public boolean checkLength(String str) {
 return str.length() > 5 && str.length() < 10;
 }
 }.checkLength("Hello");
 }
}
Which interface from the java.util.function package should you use to refactor the class Txt?

Options

  • AConsumer
  • BPredicate
  • CSupplier
  • DFunction

How the community answered

(32 responses)
  • A
    3% (1)
  • B
    9% (3)
  • C
    72% (23)
  • D
    16% (5)

Explanation

There is an error in this question: the marked correct answer (C, Supplier) is actually wrong. The correct answer is B. Predicate.

Here's the accurate explanation:

Why B (Predicate) is correct: LengthValidator.checkLength takes a String and returns a boolean - which is exactly the signature of Predicate<String>'s functional method test(String t). The refactored code would be:

Predicate<String> validator = str -> str.length() > 5 && str.length() < 10;
boolean res = validator.test("Hello");

Why the others are wrong:

  • A. Consumer<T> - takes a T but returns void, not boolean.
  • C. Supplier<T> - takes no arguments and returns a T; the opposite shape of what's needed here.
  • D. Function<T,R> - takes a T and returns an R (a general type), but when the return type is specifically boolean, Predicate is the more precise fit and the idiomatic choice.

Memory tip: Think "Predicate = passes a test." Whenever a lambda takes one input and returns true/false, reach for Predicate<T>. The other three follow the pattern: Supplier supplies (no in, something out), Consumer consumes (something in, nothing out), Function transforms (something in, something different out).

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice