Junior — Middle
Is it possible to use try-with-resources construction for automatic initialization of any classes?
sobes.tech AI
Answer from AI
The try-with-resources statement in Java is designed for automatic closing of resources that implement the java.lang.AutoCloseable interface (or Closeable).
This means that not all classes can be used with try-with-resources, only those that support the close() method, which is called automatically when exiting the try block.
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();
}
If a class does not implement AutoCloseable, it cannot be used in try-with-resources without additional wrapping.