Question 17
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
List<Supplier<Integer>> list = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
final int square = i * i; // a new final variable per iteration
list.add(() -> square);
}
int sum = 0;
for (Supplier<Integer> s : list) sum += s.get();
System.out.println(sum + " " + list.get(2).get());
}
}
- A 14 9 Correct
- B 27 9
- C 6 3
- D Compilation error
Correct Answer: Option A
Each lambda captures its own square: 1 + 4 + 9 = 14.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!