☕ Java Intermediate

What is try-with-resources in Java?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Try-with-resources (Java 7+) automatically closes resources that implement the AutoCloseable interface at the end of the try block, regardless of whether an exception is thrown. Before this feature, you had to close resources manually in finally blocks, which was verbose and error-prone. Example: try (BufferedReader br = new BufferedReader(new FileReader(file))) { return br.readLine(); }. The resource is closed automatically when the try block exits. Multiple resources can be declared: the last-declared resource is closed first. If both the try body and the close() method throw exceptions, the close() exception is suppressed (accessible via getSuppressed()).

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.