Junior — Middle
Have you used the try-with-resources construct in Java for automatic resource management?
sobes.tech AI
Answer from AI
Yes, the try-with-resources construct in Java is used for automatically closing resources that implement the AutoCloseable interface. This helps prevent resource leaks, such as open files or network connections. An 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();
}
In this example, BufferedReader will automatically close after exiting the try block, even if an exception occurs. This simplifies the code and improves resource management reliability.