Sobes.tech
Junior — Middle

What is the purpose of the AutoCloseable interface in Java and what is its feature?

sobes.tech AI

Answer from AI

The AutoCloseable interface in Java is designed for automatic resource management, such as files, network connections, or streams that require closing after use. Its feature is that objects implementing this interface can be used in a try-with-resources statement, which guarantees the close() method is called automatically, even if an exception occurs within the block.

Example:

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

This simplifies resource management and reduces the risk of leaks.

What is the purpose of the AutoCloseable interface in… - sobes.tech