nerdexam
Oracle

1Z0-819 · Question #179

Given: import java.util.function.Supplier; public class MyLambda { public static void main(String[] args) { int i = 25; Supplier<Integer> foo = () -> i; i++; System.out.println(foo.get()); } } Which…

The correct answer is C. The code does not compile. Option C is correct because Java requires variables captured by a lambda to be effectively final - meaning their value cannot change after being assigned. The line i++ modifies i after it is captured by the lambda, which violates this rule, causing a compile-time error ("local…

Working with Streams and Lambda Expressions

Question

Given: import java.util.function.Supplier; public class MyLambda { public static void main(String[] args) { int i = 25; Supplier<Integer> foo = () -> i; i++; System.out.println(foo.get()); } } Which is true?

Options

  • AThe code compiles but does not print any result.
  • BThe code prints 25.
  • CThe code does not compile.
  • DThe code throws an exception at runtime.

How the community answered

(16 responses)
  • A
    6% (1)
  • B
    13% (2)
  • C
    75% (12)
  • D
    6% (1)

Explanation

Option C is correct because Java requires variables captured by a lambda to be effectively final - meaning their value cannot change after being assigned. The line i++ modifies i after it is captured by the lambda, which violates this rule, causing a compile-time error ("local variable i defined in an enclosing scope must be effectively final").

Why the distractors are wrong:

  • A is wrong because the code never reaches runtime - the compiler rejects it outright.
  • B is wrong for the same reason; there is no execution, so nothing prints.
  • D is wrong because the failure happens at compile time, not at runtime.

Memory tip: Think of lambda captures as a "snapshot" - Java needs to guarantee the value won't change out from under the lambda, so any variable a lambda touches must be frozen (final or effectively final) from the moment of capture onward. If you see a post-capture mutation (i++, i = newValue, etc.), the code won't compile.

Topics

#lambda capture#effectively final variables#variable scope#compiler constraints

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice