Try with resource why cannot modify resource

Viewed 143

I found a try with resources example that doesn't compile when I try to set the value of the reference scan to null

try(Scanner scan = new Scanner(System.in)) {
    String s = scan.nextLine();
    System.out.println(s);
    scan = null;
}

I ask what's the rule behind this compilation error , I did some search on the net but i didn't find a rule that explain it Thanks for any explanation : =)

1 Answers

It's by design. You can't reassign a final variable.

14.20.3. try-with-resources

A variable declared in a resource specification is implicitly declared final if it is not explicitly declared final (§4.12.4).

Related