- Java 9 - Miscellaneous Features
- CompletableFuture API Improvements
- Java 9 - Multiresolution Image API
- Optional Class Improvements
- Inner Class Diamond Operator
- Enhanced @Deprecated Annotation
- Try With Resources improvement
- Java 9 - Stream API Improvements
- Java 9 - Process API Improvements
- Java 9 - Private Interface Methods
- Java 9 - Collection Factory Methods
- Java 9 - Multirelease JAR
- Java 9 - Improved JavaDocs
- Java 9 - REPL (JShell)
- Java 9 - Module System
- Java 9 - Environment Setup
- Java 9 - Overview
- Java 9 - Home
java9 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 9 - Try With Resources improvement
The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes. Any object implementing java.lang.AutoCloseable or java.io.Closeable, interface can be used as a resource.
Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we ll use BufferedReader as resource to read a string and then BufferedReader is to be closed.
Tester.java
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; pubpc class Tester { pubpc static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } }
Output
test
Here we need to declare a resource br1 within try statment and then use it. In Java9, we don t need to declare br1 anymore and following program will give the same result.
Tester.java
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; pubpc class Tester { pubpc static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } }
Output
testAdvertisements