Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javamedium

What is try-with-resources and why should you use it?

Tags
#try-with-resources#autocloseable#io
Back to categoryPractice quiz

Answer

It automatically closes resources that implement `AutoCloseable` (files, streams, JDBC) even when exceptions happen. It prevents leaks and keeps cleanup logic reliable and simple.

try (var in = Files.newInputStream(path)) {
  return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}

Advanced answer

Deep dive

Expanding on the short answer — what usually matters in practice:

  • Context (tags): try-with-resources, autocloseable, io
  • JVM: memory (heap/stack), GC, and what drives latency.
  • Contracts: equals/hashCode/toString, mutability and consequences.
  • Performance: boxing, allocations, collections, inlining.
  • Explain the "why", not just the "what" (intuition + consequences).
  • Trade-offs: what you gain/lose (time, memory, complexity, risk).
  • Edge cases: empty inputs, large inputs, invalid inputs, concurrency.

Examples

Here’s an additional example (building on the short answer):

try (var in = Files.newInputStream(path)) {
  return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}

Common pitfalls

  • Too generic: no concrete trade-offs or examples.
  • Mixing average-case and worst-case (e.g., complexity).
  • Ignoring constraints: memory, concurrency, network/disk costs.

Interview follow-ups

  • When would you choose an alternative and why?
  • What production issues show up and how do you diagnose them?

Related questions

Java
Try-with-resources: what does it require and why is it useful?
#java#exceptions#resources
Operating Systems
What is memory-mapped I/O (mmap) and when would you use it?
#mmap#memory#io
Operating Systems
What are file descriptors and how does I/O buffering work?
#file-descriptors#io
  • How would you test edge cases?
  • #buffering