Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Scope and lifetime

Scope and lifetime: Lexical scope determines where a name is visible, while object lifetime follows reachability; try-with-resources closes a resource deterministically.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

scope lifetime

Lexical scope determines where a name is visible, while object lifetime follows reachability; try-with-resources closes a resource deterministically.

Capturing a local variable from a lambda, local class, or anonymous class requires final or effectively final local capture under JLS 4.12.4.

A local variable has no default value and must be definitely assigned; reassigning a captured variable removes its effectively final status.

Resources close in reverse order and an object can outlive its block through a reference; a close exception can be suppressed by an earlier exception.

The lambda legally captures the unchanged prefix and prints ID-7; leaving try-with-resources immediately calls close and adds closed.

Examples

public class Main {
    static final class Resource implements AutoCloseable {
        public void close() {
            System.out.println("closed");
        }
    }

    public static void main(String[] args) {
        String prefix = "ID-";
        java.util.function.IntFunction<String> label = number -> prefix + number;
        try (Resource ignored = new Resource()) {
            System.out.println(label.apply(7));
        }
    }
}

Result

ID-7
closed

The lambda legally captures the unchanged prefix and prints ID-7; leaving try-with-resources immediately calls close and adds closed.

Sources