Course contentsShow
← Java
Lesson 1949 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Effectively Final Resources (Java 9+)

Referencing existing effectively final stream variables in try-with-resources without re-declaration.

Effectively Final Resources (Java 9+)

You'll learn how Java 9+ lets you reference existing variables directly in try-with-resources without redundant declarations.

The Old Way vs The New Way

Before Java 9, if you already had a stream variable created outside the try block, you couldn't reference it directly in try-with-resources. You had to create a new variable inside the try parentheses, which felt redundant:

FileInputStream fis = new FileInputStream("data.bin");
// Had to do this in Java 7-8:
try (FileInputStream newFis = fis) {
    // Use newFis...
}

This created unnecessary duplication just to satisfy the syntax.

Effectively Final to the Rescue

Starting in Java 9, if your resource variable is effectively final (never reassigned after initialization), you can reference it directly in the try-with-resources statement:

FileInputStream fis = new FileInputStream("data.bin");
BufferedInputStream bis = new BufferedInputStream(fis);

// Java 9+: Use existing variables directly!
try (fis; bis) {
    // Read from bis...
    byte[] buffer = new byte[1024];
    int bytesRead = bis.read(buffer);
}
// Both fis and bis are automatically closed

Notice the semicolons separating multiple resources—no need to re-declare or assign anything.

What "Effectively Final" Means

A variable is effectively final if you never reassign it after initialization. You don't need the final keyword; Java just checks that the reference never changes:

FileOutputStream fos = new FileOutputStream("output.dat"); // effectively final
// fos = something else; // ❌ Would break effectively final status

try (fos) { // ✅ Works because fos is effectively final
    fos.write(65);
}

Key Takeaway: Java 9+ allows you to use existing effectively final resource variables directly in try-with-resources without re-declaring them, reducing boilerplate and making your code cleaner.