Senior
In which version of Java was AutoCloseable introduced?
sobes.tech AI
Answer from AI
The AutoCloseable interface was introduced in Java starting from version 7 (Java SE 7). It allows objects to be automatically closed when used in a try-with-resources statement, simplifying resource management and preventing leaks.
Example of usage:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here, BufferedReader implements AutoCloseable, and the resource is automatically closed after the try block.