1Z0-819 Lambda Expressions 2 — Questions and Answers
Question 1: Which functional interface should you use when a lambda takes two arguments of the same type and returns a result of the same type?
- BiFunction<T,T,T>
- BinaryOperator<T> (Correct answer)
- BiConsumer<T,T>
- UnaryOperator<T>
Correct answer: BinaryOperator<T>
BinaryOperator<T> extends BiFunction<T,T,T> and is the correct specialization when both inputs and output share the same type.
Question 2: What is the result of compiling and running: Predicate<String> p = String::isEmpty; System.out.println(p.test(""));
- false
- true (Correct answer)
- Compilation error
- NullPointerException
Correct answer: true
String::isEmpty is a valid method reference to an instance method, and calling test("") invokes isEmpty() on the empty string, returning true.
Question 3: Which statement about a lambda expression and its enclosing scope is TRUE?
- A lambda creates a new scope so it can redeclare variables from the enclosing scope.
- A lambda can modify local variables from the enclosing scope.
- Local variables captured by a lambda must be effectively final. (Correct answer)
- A lambda cannot access instance variables of the enclosing class.
Correct answer: Local variables captured by a lambda must be effectively final.
Lambdas can only capture local variables that are final or effectively final; instance and static variables are freely accessible.
Question 4: Given: Function<Integer, Integer> f = x -> x * 2; Function<Integer, Integer> g = x -> x + 3; what does f.andThen(g).apply(5) return?
- 13 (Correct answer)
- 16
- 10
- 11
Correct answer: 13
andThen applies f first (5*2=10) then g (10+3=13).
Question 5: Which of the following is NOT a valid lambda expression in Java 11?
- () -> {}
- x -> x + 1
- (int x, y) -> x + y (Correct answer)
- (int x, int y) -> x + y
Correct answer: (int x, y) -> x + y
When parameter types are explicitly listed you must provide types for all parameters; mixing typed and untyped parameters is a compile error.
Question 6: What does Predicate.not(Predicate) introduced in Java 11 do?
- Negates a predicate returning a new Predicate (Correct answer)
- Composes two predicates with logical AND
- Returns a Predicate that always returns false
- Throws an exception if the predicate is null
Correct answer: Negates a predicate returning a new Predicate
Predicate.not(p) is a static factory that returns a new Predicate which is the logical negation of the given predicate.
Question 7: Which functional interface represents a supplier that may throw a checked exception when used in a custom functional interface?
- Supplier<T>
- Callable<T> (Correct answer)
- Consumer<T>
- Function<T,T>
Correct answer: Callable<T>
Callable<T> declares throws Exception on its call() method, while Supplier's get() does not declare a checked exception.
Which functional interface should you use when a lambda takes two arguments of the same type and returns a result of the same type?