Blog

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

© 2025 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);
}

Related questions

Java
Try-with-resources: what does it require and why is it useful?
#java#exceptions#resources