Interview Question

What is try-with-resources?

try-with-resources closes AutoCloseable resources automatically.

💡 Concept ✅ Quick Revision ☕ Java

Answer

A try-with-resources statement automatically closes resources that implement AutoCloseable. • Resources are closed in reverse declaration order. • Closing happens whether the try body completes normally or abruptly. • Close failures can become suppressed exceptions when another exception is already pending.

Example

Code
try (var reader = new java.io.StringReader("Java")) {
    System.out.println((char) reader.read());
}
Output
J

Quick Revision

try-with-resources closes AutoCloseable resources automatically.