Try With Resources Java 9 Enhancement: A Simple, Hands-On Guide
-
Last Updated:
-
By: Suraj S R
-
Series

Learn the try with resources java 9 enhancement in simple words. Use final or effectively final variables directly in the try block, with clear examples.
The try with resources java 9 enhancement is one of those small changes you grow to love. It does not add any big new feature. Instead, it cleans up code you already write every day. Have you ever opened a file, a database connection, or a socket in Java? Then you have met this problem before. You open something, you use it, and then you must close it. Closing sounds easy, but it goes wrong more often than people admit.
In older Java, we used to write long try-catch-finally blocks just to close one stream. Java 7 made life better with the first try-with-resources statement. Then Java 9 came and polished it a little more. So in this guide, we will go slow and build the idea from the ground up. We will start with the old pain, move to Java 7, and finally reach the neat Java 9 style.
This article is written for beginners. Therefore, I will keep the words plain and the examples small. You do not need to be an expert to follow along. You only need to know what a try block is and what a method call looks like. Let us begin with the basic problem of resources.
A resource is anything that your program holds and must give back later. Think of it like borrowing a book from a library. You take the book, you read it, and then you return it. If you forget to return it, the library runs out of books for others. Your computer works the same way with files and connections.
Here are some common examples of resources:
All of these hold something outside your program. A file holds a handle from the operating system. A connection holds a slot on the database server. These slots are limited. So when you are done, you must release them. Otherwise, your app slowly leaks resources and later it crashes.
In Java, a resource is any object that implements the AutoCloseable interface. This interface has just one method, named close(). The Closeable interface, used for I/O streams, extends AutoCloseable too. Because of this, files, streams, and many connections already fit the pattern. That one detail is the key to everything that follows.
| 💡 INTERVIEW INSIGHT Interviewers love to ask: what makes a class usable in try-with-resources? The short answer is that it must implement AutoCloseable (or its sub-interface Closeable). The compiler then calls close() for you automatically. Mention that Closeable.close() throws IOException while AutoCloseable.close() throws a broader Exception. |
Before Java 7, we had no clean tool for closing resources. So we leaned on the finally block. The idea was simple on paper. You open the resource inside try, and you close it inside finally. The finally block always runs, so the resource always gets closed. Sadly, the real code looked ugly and it broke in strange ways.
Let us look at a plain example. Here we read one line from a file using the old style.
// Java 6 style: read one line from a file
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("data.txt"));
String firstLine = reader.readLine();
System.out.println(firstLine);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); // close() can also throw IOException
} catch (IOException ex) {
ex.printStackTrace();
}
}
}Look at all that code for one small job. We declared the reader outside the try so that finally could see it. Then we checked for null, because the reader may never get created. After that, we wrapped close() inside another try-catch, because close() itself can throw an error. It is a lot of noise for a simple read.
There is a deeper problem too, and it is sneaky. Suppose readLine() throws an error, and then close() also throws an error. In that case, the second error hides the first one. So you lose the real reason your code failed. Many developers spent hours chasing bugs because of this very thing.
Java 7 arrived and solved most of this mess. It gave us the try-with-resources statement. The idea is lovely. You declare your resource inside a pair of round brackets right after the try keyword. Then Java closes it for you, automatically, when the block ends. You no longer write a finally block just to close things.
Here is the same file-reading task, now in Java 7 style.
// Java 7 style: resource declared inside try ( ... )
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String firstLine = reader.readLine();
System.out.println(firstLine);
} catch (IOException e) {
e.printStackTrace();
}
// reader.close() is called automatically hereSee how short that is now. We put the reader inside try(…). When the block finishes, Java calls close() on its own. This happens whether the block ends normally or throws an error. As a result, the resource never leaks, and we write far less code.
The Java 7 version fixed the hidden-error problem too. If your main code throws an error and close() also throws, Java keeps the first error. The close() error is not lost, though. It gets attached as a suppressed exception. You can still read it later with getSuppressed(). So nothing is thrown away silently.
You can also declare more than one resource at once. Just separate them with a semicolon. Java then closes them in reverse order, which is the safe order. The last one opened is the first one closed. Reverse order matters when one resource wraps another. An outer stream often needs the inner one open while it flushes.
// Java 7: two resources, closed in reverse order
try (FileInputStream in = new FileInputStream("in.txt");
FileOutputStream out = new FileOutputStream("out.txt")) {
// copy logic goes here
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
// out.close() runs first, then in.close()| 💡 INTERVIEW INSIGHT A classic question: in what order are resources closed in a try-with-resources block? Answer confidently that they close in the reverse order of declaration. The resource declared last is closed first. This order keeps wrapper streams safe and avoids closing an inner stream too early. |
Java 7 was great, but it had one small rule that annoyed people. You had to declare the resource right inside the try brackets. You could not just pass in a resource that already existed somewhere else. So if you already had a resource variable, you had to make a new dummy name for it.
Let us see why that felt silly. Imagine a method hands you a resource. You want to use it in a try-with-resources block. In Java 7, you could not simply write the variable name. You had to re-declare it with a fresh name, like this.
// Java 7 / Java 8: you must re-declare the resource
// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");
// You cannot write try (resource1; resource2)
// So you create extra names r1 and r2:
try (Resource r1 = resource1;
Resource r2 = resource2) {
// use r1 and r2 here
}Notice the names r1 and r2. They add nothing useful. They only exist to satisfy the old rule. For one resource it is minor, but for two or three it starts to clutter the code. Developers asked the Java team for something cleaner, and the team agreed.
This example comes straight from the official Oracle documentation. It shows one final resource and one effectively final resource. Both of them had to be re-declared before Java 9. Keep this example in mind, because the Java 9 version removes exactly this noise.
Now we reach the heart of this guide. Java 9 made one targeted change to try-with-resources. The try with resources java 9 rule is short and sweet. You may now use a final or effectively final variable right inside the try brackets. You do not re-declare it. Simply write its name, and Java closes it for you. That is the whole enhancement in one line.
Let us rewrite the earlier example in the new style. The two resources stay where they are. We simply name them inside try(…).
// Java 9 and later: use existing final / effectively final variables
// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");
// New and improved try-with-resources in Java 9:
try (resource1;
resource2) {
// use resource1 and resource2 here
}
// Java still calls close() on both, in reverse orderMuch cleaner, right? The r1 and r2 names are gone. You read the code and you instantly know which objects are in play. Behind the scenes, nothing changed about safety. Java still calls close() on both resources, still in reverse order, still with suppressed exceptions handled correctly.

This change came from a project called Milling Project Coin. The goal of that project was to smooth out small rough edges in the language. In the official issue tracker, it is listed as JDK-7196163. The matching language spec change lives in JLS section 14.20.3. So this is a real, documented language rule, not a trick.
You will hear the phrase effectively final a lot here, so let us pin it down. A variable is effectively final when you assign it once and never change it after that. You do not have to write the final keyword. You just never reassign the variable. The compiler checks this for you.
Here is a quick way to see the difference. The first variable is final by keyword. The second one is effectively final by behavior. Both work in Java 9 try-with-resources.
// final by keyword
final BufferedReader r1 = new BufferedReader(new FileReader("a.txt"));
// effectively final: assigned once, never changed again
BufferedReader r2 = new BufferedReader(new FileReader("b.txt"));
// Both can be used directly in Java 9:
try (r1; r2) {
System.out.println(r1.readLine());
System.out.println(r2.readLine());
}Now watch what breaks the rule. If you reassign the variable after creating it, it is no longer effectively final. The compiler will then reject it inside try-with-resources. This guard exists for a good reason, which we will cover next.
BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
reader = new BufferedReader(new FileReader("b.txt")); // reassigned!
// Compile error: variable used as a try-with-resources
// resource is not final or effectively final
try (reader) {
// ...
}| 💡 INTERVIEW INSIGHT Expect this trap: can you use any variable in a Java 9 try-with-resources header? No. It must be final or effectively final. If asked why, explain that Java must close exactly the object it opened. If the variable could change mid-block, it would be unclear which object close() should act on. The final rule removes that ambiguity cleanly. |
At first, the final rule may feel like a random limit. But there is clear logic behind it. Java needs to know exactly which object to close. If you could change the variable in the middle of the block, confusion would follow. Should Java close the first object or the new one? That question has no safe answer.
So the language keeps it simple. The resource variable must point to one object for the whole block. Because of this, the final or effectively final rule is the natural choice. It guarantees that the object you open is the exact object that gets closed. No surprises, no leaks, no guessing.
The Java team also kept one older limit on purpose. You still cannot drop a raw method call into the try header. For example, this is still not allowed:
// Still NOT allowed, even in Java 9+
try (getResource()) { // compile error
// ...
}
// You must assign it to a variable first:
MyResource res = getResource();
try (res) { // this works
// ...
}Why block the direct method call? Because a method result has no stable name to refer back to. Java prefers a named, final variable, so the rule stays strict here. This was a conscious design choice during Java 7, and Java 9 did not loosen it. Only the final-variable path was added.
Before you try the new syntax, make sure your Java version supports it. The feature needs Java 9 at least. Most developers today run Java 17, 21, or 25, so you are likely fine. Still, it is good to confirm. Open a terminal and run one simple command.
java -version # Sample output: # openjdk version "21.0.2" 2024-01-16 # This is newer than 9, so the Java 9 syntax works.
If the number is 9 or higher, you are ready. If it shows 8 or lower, you must upgrade first. On Java 8, the new syntax will not compile. In that case, fall back to the Java 7 style with declared resource names. Once you upgrade, switch to the cleaner form.
Let us put everything together in one small program. We will create a tiny resource class so you can run this without any file on disk. The class prints a message when it opens and another when it closes. That way, you can see the close order with your own eyes.
public class TryWithResourcesJava9 {
// A simple resource that logs open and close
static class MyResource implements AutoCloseable {
private final String name;
MyResource(String name) {
this.name = name;
System.out.println("Opened: " + name);
}
void use() {
System.out.println("Using: " + name);
}
@Override
public void close() {
System.out.println("Closed: " + name);
}
}
public static void main(String[] args) {
// effectively final: created once, never reassigned
MyResource first = new MyResource("first");
MyResource second = new MyResource("second");
// Java 9 style: reuse the existing variables directly
try (first; second) {
first.use();
second.use();
}
}
}Run this program on Java 9 or any newer version. You will see a clear sequence in the console. First both resources open. Then both get used. Finally, they close in reverse order. The output tells the whole story without any extra explanation.
Opened: first Opened: second Using: first Using: second Closed: second Closed: first
Notice the last two lines closely. The second resource closes before the first one. This proves the reverse-order rule we talked about earlier. Even though we used the short Java 9 syntax, the safe close order stayed exactly the same. Clean code, same guarantees.
Sometimes a quick comparison helps the idea stick. So here is a short rundown of what changed and what stayed the same. The core behavior did not move at all. Only the amount of code you write went down.
In short, Java 9 is pure polish. The safety story is the same, so you lose nothing by using it. You only gain shorter, clearer code. For a beginner, that is a sweet deal. You get a cleaner tool without any new risk.
Even with this neat syntax, a few mistakes show up again and again. Let us go through them so you can dodge each one. These are the traps I have seen in real code reviews. None of them are hard to fix once you know about them.
The most common slip is changing the variable after you create it. The moment you reassign it, it stops being effectively final. Then the compiler refuses to use it in the try header. If you hit this error, look for a second assignment to the same variable. Remove it, or use a new variable instead.
Some people try to write try(openFile()) and expect it to compile. As we saw, that is still not allowed. Always assign the result to a final or effectively final variable first. Then put that variable name inside the try brackets. It is a tiny extra step, but it keeps the compiler happy.
A few beginners think close() only runs when the block succeeds. That is wrong. Java calls close() even when your code throws an error. So you never need a finally block just to close the resource. Trust the try-with-resources statement to do its job in every case.
| 💡 INTERVIEW INSIGHT A tricky follow-up: if both the try body and close() throw exceptions, which one does the caller see? The caller sees the exception from the try body. The close() exception is attached to it as a suppressed exception. You can read suppressed exceptions through the getSuppressed() method on the thrown Throwable. |
You might wonder where this shows up in real work. The answer is almost everywhere you touch I/O. Any time you open something that must be closed, this pattern fits. So it pays to make the Java 9 style a habit early. Your future code will be cleaner for it.
In a Spring Boot or plain Java project, you will meet resources daily. A JDBC Connection, a PreparedStatement, and a ResultSet are all AutoCloseable. You can open them, use them, and let try-with-resources close them in the right order. That keeps your data layer tidy and leak-free.
Here is a small JDBC example in the Java 9 style. Suppose a helper method hands you an open connection. You keep it in an effectively final variable, then name it in the try header. The statement and result set go inside the same try. All three then close automatically, in reverse order, when the block ends.
// JDBC with the Java 9 try-with-resources style
Connection conn = dataSource.getConnection(); // effectively final
try (conn;
PreparedStatement ps = conn.prepareStatement("SELECT name FROM users");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
// rs closes first, then ps, then connRead that example slowly. The connection already exists before the try starts. We reuse it by name, which is the Java 9 touch. The statement and result set are fresh, so we declare them normally. In the end, all three close in the safe reverse order without a single finally block.
As a small note, the Java team itself adopted this style inside the JDK. The issue JDK-8068948 updated the core java.base module to use the new syntax. So this is not just a classroom trick. It is the same style the language authors use in production code.
A: In Java 9 you can use a final or effectively final variable directly inside the try brackets, without re-declaring a new resource variable. Java still calls close() automatically when the block ends.
A: A variable is effectively final when you assign it once and never change it again. You do not need the final keyword. The compiler checks this for you, and such a variable can be used in a Java 9 try-with-resources header.
A: No. Writing try(getResource()) still does not compile, even in Java 9. You must assign the result to a final or effectively final variable first, then name that variable inside the try brackets.
A: Resources close in the reverse order of declaration. The resource declared last is closed first. This keeps wrapper streams safe and avoids closing an inner stream too early.
A: You need Java 9 or newer. On Java 8 or lower the new form will not compile, so you must declare resource names the Java 7 way. Run java -version to check what you have.
Let us bring the whole journey together in a few lines. We started with the messy try-catch-finally style from the old days. Then Java 7 gave us automatic closing with try-with-resources. After that, Java 9 trimmed one small annoyance by allowing final and effectively final variables directly. Each step made resource handling a little safer and a little simpler.
For a beginner, the lesson is easy to carry. Always close what you open, and let Java do the closing for you. Use the try-with-resources java 9 style whenever your resource already lives in a final or effectively final variable. Your code gets shorter, and your bugs get fewer. That is a win you will feel on day one.
Try the full example above on your own machine. Watch the open and close messages print in order. Once you see it work, the idea will stick for good. From there, you can carry the same habit into files, databases, and every other resource you meet.