Sobes.tech
Junior — Middle

Explain the principle of automatic resource closing in Java using try-with-resources.

sobes.tech AI

Answer from AI

The try-with-resources statement in Java allows automatic closing of resources that implement the AutoCloseable interface (such as streams, database connections).

Syntax:

try (ResourceType resource = new ResourceType()) {
    // work with the resource
}
// resource is automatically closed here

Working principle:

  • The resource is declared in parentheses after try.
  • After the try block executes (even if an exception occurs), the close() method is called on the resource.
  • This prevents resource leaks and simplifies code by eliminating the need for finally blocks to close resources.

Example:

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}
// reader.close() is called automatically