LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Find the Error · Question 9

Error: a lambda capturing a reassigned variable Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int total = 0;
        List.of(1, 2, 3).forEach(n -> total += n);
        System.out.println(total);
    }
}
  • A forEach needs a Consumer class
  • B A lambda can only use final or effectively final local variables, and total is modified; use a stream sum() or an AtomicInteger Correct
  • C List.of is immutable
  • D n must be declared int
Correct Answer: Option B

Write int total = List.of(1, 2, 3).stream().mapToInt(Integer::intValue).sum();

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