LearnFrenzy
Sign in Take a free test

Lambda Expressions · Find the Error · Question 1

Error: reassigning a variable after a lambda captured it Answer, explanation & discussion

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

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

Main.java
public class Main {
    public static void main(String[] args) {
        String prefix = ">";
        Runnable r = () -> System.out.println(prefix + " ready");
        prefix = ">>";
        r.run();
    }
}
  • A Runnable cannot print
  • B prefix is reassigned later, so it is not effectively final and cannot be captured by the lambda Correct
  • C println needs a String variable
  • D r must be final
Correct Answer: Option B

javac: "local variables referenced from a lambda expression must be final or effectively final".

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