In this tutorial, we’re going to get through how to use effectively final variables in the try-with-resources statement in Java 9.

1. The try-with-resources Statement In Java

The try-with-resources statement is a try statement that declares one or more resource and ensures that each resource will be closed at the end of the statement. Any object that implements java.lang.AutoCloseable interface such as FileReader, BufferedReader, BufferedWriter, etc, can be used with the try-with-resources statements.

The following example reads contents of the application-prod.properties file and writes to the application-backup.properties file. It uses instances of the BufferedReader, BufferedWriter classes to read and write data from and to files. The BufferedReader, BufferedWriter are resources that must be closed after the program is finished with them:

2. The try-with-resources Improvement In Java 9

Before getting to the try-with-resources improvement in Java 9, let’s see an example which we use Java 7 to read contents from two files: application-prod.properties, application-qa.properties and then write to application-backup.properties file:

We can see that the brTmp which is a resource declared and used in the first try-with-resources statement, can not be used directly in the second try-with-resources statement even it’s a final variable.

In Java 9,  the try-with-resources statement has been improved. If we already have a resource as a final or effectively final variable, we can use that variable in the try-with-resources statement without declaring a new variable in the try-with-resources statement, for example:

We can see that because the backupBw is an effectively final variable, we can use it directly in the try-with-resources statement without declaring a new variable as the previous example.

3. Conclusions

The tutorial has illustrated us the try-with-resources improvement in Java 9. We can see that even this is not a big change in Java 9, but this gives us a more concise way when we work with the try-with-resource statement in Java.

The source code presented in the tutorial is available on my Github project. It’s a Maven based project, so it’s easy to be imported into IDE such as Eclipse, IntelliJ, etc.

Below are other related articles for your references:

Java 9 Tutorial

Install Oracle Java 9 on CentOS, RHEL 7

Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)

Set Up Eclipse, IntelliJ And NetBeans For Java 9

Java 9 Example With Maven And JUnit 5

Java 9 JShell Cheat Sheet

Create Immutable Lists In Java 9 By Static Factory Methods

Private Interface Methods In Java 9

Using The InputStream.transferTo() To Copy Streams In Java 9

Java 9 – New Methods Of The Optional Class

Streams API Updates In Java 9

Java 9 HTTP/2 Client API Example

 

0 0 vote
Article Rating