Junior — Middle
How can automatic resource release be ensured in a program?
sobes.tech AI
Answer from AI
In Java, automatic resource management is usually provided by the try-with-resources statement, introduced in Java 7. It allows resources that implement the AutoCloseable interface (such as input/output streams, database connections, etc.) to be automatically closed after the try block, even if an exception occurs inside the block.
Example:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
// reader is automatically closed here
Previously, resources were released using a finally block where the close() method was explicitly called. But try-with-resources makes the code cleaner and safer.