Sobes.tech
Junior — Middle

Can you explain what the Closeable interface in Java represents?

sobes.tech AI

Answer from AI

The Closeable interface in Java defines a single method close(), which is used to release resources, such as closing file streams, network connections, and other input-output resources. It is located in the java.io package.

A key feature of Closeable is its use in the try-with-resources statement, which automatically calls the close() method after the resource is no longer needed, helping to prevent resource leaks.

Example of usage:

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

Thus, Closeable is a contract for objects that need to be closed after use.