Sobes.tech
Junior — Middle

Explain the principle of using try-with-resources in Java for resource management.

sobes.tech AI

Answer from AI

The try-with-resources construct in Java is used for automatic closing of resources that implement the AutoCloseable interface (for example, input/output streams, database connections). Resources are declared in parentheses after the try keyword, and after the try block completes (regardless of whether an exception was thrown), the close() method is automatically called for each resource. This simplifies resource management and prevents leaks.

Example:

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