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.
Previous
What is the difference between List.of() and Arrays.asList()?
Next
What is PriorityQueue in Java?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?