ProgrammingModerateAmazon/Microsoft SDE MCQ · Java placement

Which line fails to compile?

Which line fails to compile?
int base = 10;
int step = 1;
step = 2;
Function<Integer, Integer> f = x -> x + base;   // line 1
Function<Integer, Integer> g = x -> x + step;   // line 2
Runnable r = () -> { int base2 = base; };      // line 3
  1. A. Line 1
  2. B. Line 3
  3. C. Line 2
  4. D. Lines 1 and 3

Correct answer: C. Line 2

A lambda may only capture local variables that are final or effectively final. base is never reassigned, so lines 1 and 3 are fine; step is reassigned, so capturing it on line 2 is an error.

More OOP with C++ and Java questions

Exams that ask this topic