Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> xs = List.of(1, 2, 3);
int total = 0;
xs.forEach(x -> total += x);
System.out.println(total);
}
}It does not compile
- Expecting
6: a lambda is not a loop body; it may read local variables of the method but not assign to them, sototal += xdoes not compile. - Expecting an error only when
forEachruns: the effectively final rule is checked by the compiler, so the program never starts.
- How can you sum the list without changing a local variable from a lambda?
- Why does Java require a local variable used in a lambda to be effectively final?