Java 9 Try with Resource Enhancement

By | June 27, 2021

Java introduced try-with-resources feature in Java 7 that helps to close resources automatically after being used.

In other words, we can say that we don’t need to close resources (file, connection etc) explicitly, try-with-resource close that automatically by using the AutoClosable interface.

If you look in Java 7 then you will find that try-with-resources has a limitation that It requires resources to declare locally within its block Like below.

Example Java 7 Resource Declared within resource block

try(FileOutputStream fileStream=new FileOutputStream(“test.txt”);){ 

}

This code will be executed fine in Java 7 and even with Java 9 because Java maintains its legacy or backward compatibility.

But the below program would not work with Java 7 because we can’t put resource declared outside the try-with-resource.

If we execute this code in Java 7, the compiler generates an error message.

 FileOutputStream fileStream=new FileOutputStream(“test.txt”);  

  try(fileStream){

}

To overcome this error, try-with-resource is enhanced in Java 9 and now we can use reference of the resource that is not declared locally.

test.txt

Java9TryWithResourcTest.java

If you run Java9TryWithResourcTest.java as Java Application then it will give the below output:

That’s all about Java 9 Try with Resource Enhancement

You May Also Like:

Java 9 Jshell Tutorial
Java 9 private Methods in Interfaces
Java 9 @SafeVarargs Annotation
Java 9 Collection Factory Methods
Java 9 Stream API improvements

If you have any feedback or suggestion please feel free to drop in below comment box. 

Leave a Reply

Your email address will not be published.