Sobes.tech
Junior — Middle

Can you explain what the Closable interface is and how it is used?

sobes.tech AI

Answer from AI

In Java, the interface Closable (correct name — Closeable) defines a contract for objects that can be closed, releasing associated resources such as input/output streams.

It contains one method:

void close() throws IOException;

This method is called to release resources when the object is no longer needed.

The Closeable interface is often used with the try-with-resources statement, which automatically closes resources after use:

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

Here, BufferedReader implements Closeable, and the close() method is called automatically at the end of the try block, helping to prevent resource leaks.

Can you explain what the Closable interface is and… - sobes.tech