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
tryblock executes (even if an exception occurs), theclose()method is called on the resource. - This prevents resource leaks and simplifies code by eliminating the need for
finallyblocks 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