Pre-Initialized Resources (Java 9+)
What you'll learn: How to use already-initialized variables in try-with-resources statements without declaring them again.
The Old Way vs The New Way
Before Java 9, if you had a resource variable already initialized, you had to either manage it manually or awkwardly re-declare it in the try-with-resources parentheses. Java 9 introduced a cleaner approach: you can now reference effectively final or final variables directly in the try-with-resources statement.
What Does "Effectively Final" Mean?
A variable is effectively final if it's never reassigned after initialization. Think of it like this: once you put a book on a shelf, you never move it to a different shelf. The reference stays constant, even though you haven't explicitly declared it final.
The Syntax
Instead of creating a new variable inside the try parentheses, you simply reference your existing variable:
FileInputStream input = new FileInputStream("data.txt");
// Java 9+: Use the pre-initialized resource directly
try (input) {
// Use input here
int data = input.read();
}
// input.close() is called automatically
You can also mix pre-initialized and newly declared resources:
FileInputStream input = new FileInputStream("data.txt");
try (input; FileOutputStream output = new FileOutputStream("out.txt")) {
// Both resources are automatically closed
}
Why This Matters
This feature eliminates boilerplate code when you need to initialize resources before the try statement—perhaps because initialization logic is complex, or you need the resource reference elsewhere first. It keeps your code cleaner and more readable.
Key Takeaway: In Java 9+, you can use effectively final or final resource variables directly in try-with-resources without re-declaring them, as long as the variable isn't reassigned after initialization.