nerdexam
Oracle

1Z0-808 · Question #45

Person.java: public class Person { String name; int age; public Person(String n, int a) { name = n; age = a; } public String getName() { return name; } public int getAge() { return age; } }…

The correct answer is C. checkAge (iList, p-> p.getAge() > 40). Option C uses the correct lambda syntax for a Predicate<Person>: a single inferred-type parameter without parentheses, followed by an expression body that directly returns a boolean - which is exactly what Predicate<Person>.test(Person p) requires. Since Hank is 45, 45 > 40…

Working with Methods and Encapsulation

Question

Person.java: public class Person { String name; int age; public Person(String n, int a) { name = n; age = a; } public String getName() { return name; } public int getAge() { return age; } } Test.java: public static void checkAge(List<Person> list, Predicate<Person> predicate) { for (Person p : list) { if (predicate.test(p)) { System.out.println(p.name + " "); } } } public static void main(String[] args) { List<Person> iList = Arrays.asList(new Person("Hank", 45), new Person("Charlie", 40), new Person("Smith", 38)); //line n1 } Which code fragment, when inserted at line n1, enables the code to print Hank?

Options

  • AcheckAge (iList, () -> p. get Age () > 40);
  • BcheckAge (iList, Person p -> p.getAge() > 40);
  • CcheckAge (iList, p-> p.getAge() > 40);
  • DcheckAge (iList, (Person p) -> {p.getAge() > 40;});

How the community answered

(33 responses)
  • A
    9% (3)
  • B
    3% (1)
  • C
    73% (24)
  • D
    15% (5)

Explanation

Option C uses the correct lambda syntax for a Predicate<Person>: a single inferred-type parameter without parentheses, followed by an expression body that directly returns a boolean - which is exactly what Predicate<Person>.test(Person p) requires. Since Hank is 45, 45 > 40 evaluates to true, so he gets printed.

Why the others fail:

  • A uses () (no parameters), but Predicate<Person> requires exactly one Person argument - this won't compile.
  • B is a syntax error: when you explicitly declare the parameter type, parentheses are mandatory - it must be (Person p), not Person p.
  • D uses a block body {...} but omits return. Inside a block body, you must write return p.getAge() > 40; - without it, the lambda returns void, which doesn't satisfy Predicate<Person>.

Memory tip: Think of the lambda rules as "brackets need brackets" - explicit type needs (), block body needs return. When in doubt, the simplest form p -> expression is always valid for a single-parameter predicate.

Topics

#Lambda expressions#Predicate interface#Functional interfaces#Type inference

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice