LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Predict the Output · Question 17

Lambdas capturing a final loop variable Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links