BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 9 – Try With Resources Enhancements

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: java

Try with resource statement was first introduced in Java 7. This statement has received a major enhancement in Java 9. In this guide, we will discuss the improvements of try-with-resource statement in Java 9.

What is Try-With-Resources?

This statement was first introduced in Java 7 to avoid the redundant code that we had to write for exception handling. The advantages of this statement are:
1. Try with resources closes all the resources (file, database connection, network connection etc.) automatically. No need to close them explicitly. This prevents memory leaks.
2. With the help of try with resource we can reduce the unnecessary lines of code and makes the code more readable.

How we used to write the code in Java 7 using Try-With-Resources?

This is how we use the Try-With-Resource statement in Java 7.

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class JavaExample {  
    public static void main(String[] args) throws FileNotFoundException {  
        try(FileOutputStream fileOutputStream = new FileOutputStream("beginnersbook.txt");){ 
             //We are writing this string in the output file using FileOutputStream
             String mystring = "We are writing this line in the output file."; 
             
             //Converting the given string in bytes
             byte bytes[] = mystring.getBytes();       
             
             //Writing the bytes into the file
             fileOutputStream.write(bytes);      
             
             //Displaying success message after the successful write operation
             System.out.println("The given String is written in the file successfully");           
        }catch(Exception e) {  
            System.out.println(e);  
        }         
    }  
}

Output:

The given String is written in the file successfully

Problem with the Try-With-Resources in Java 7

There were certain issues with the Try-With-Resource statement in Java 7. This statement didn’t allow the resources to be declared outside of the statement block (scope). Lets take an example to understand this.

Java 7 – Resource declared outside the Try-With-Resources block

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class JavaExample {  
    public static void main(String[] args) throws FileNotFoundException { 
       FileOutputStream fileOutputStream = new FileOutputStream("beginnersbook.txt");
       try(fileOutputStream){ 
            String mystring = "We are writing this line in the output file."; 
            byte bytes[] = mystring.getBytes();       
            fileOutputStream.write(bytes);      
            System.out.println("The given String is written in the file successfully");           
        }catch(Exception e) {  
            System.out.println(e);  
        }         
    }  
}

Output in Java 7:

Compile-time error

The above example throws compile-time error because the resource is declared outside the scope of Try-With-Resource statement.

Java 7 – Resource declared outside – duplicate resource as workaround
To solve the above error, we had to do a workaround in Java 7. We used to duplicate the resource reference like this:

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class JavaExample {  
    public static void main(String[] args) throws FileNotFoundException { 
       FileOutputStream fileOutputStream = new FileOutputStream("beginnersbook.txt");
       try(FileOutputStream fileOutputStream2 = fileOutputStream){ 
            String mystring = "We are writing this line in the output file."; 
            byte bytes[] = mystring.getBytes();       
            fileOutputStream2.write(bytes);      
            System.out.println("The given String is written in the file successfully");           
        }catch(Exception e) {  
            System.out.println(e);  
        }         
    }  
}

This code would run fine in Java 7.
Note the FileOutputStream fileOutputStream2 = fileOutputStream line in the try block. We created another reference to the already declared output stream within the scope of Try-With-Resource.

Java 9 – Try-With-Resources Enhancements

Java 9 provided a major enhancement to the traditional Try-With-Resource statement. Java 9 allows us to declare the resource outside of the Try-With-Resource block. We no longer need to create the local variable to access the resource. Lets take the same example that we have taken in Java 7 but got a compilation error. In Java 9, this code runs perfectly fine.

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class JavaExample {  
    public static void main(String[] args) throws FileNotFoundException { 
       FileOutputStream fileOutputStream = new FileOutputStream("beginnersbook.txt");
       try(fileOutputStream){ 
            String mystring = "We are writing this line in the output file."; 
            byte bytes[] = mystring.getBytes();       
            fileOutputStream.write(bytes);      
            System.out.println("The given String is written in the file successfully");           
        }catch(Exception e) {  
            System.out.println(e);  
        }         
    }  
}

Output:

The given String is written in the file successfully

Screenshot of this code in Eclipse Oxygen running Java SE 9.
Java 9 - Try with resources enhancements

Top Related Articles:

  1. Java 8 – Stream Collectors Class with examples
  2. How to read file in Java using BufferedReader
  3. Exception handling in Java with examples
  4. Java Exception Handling Examples
  5. Nested try catch block in Java – Exception handling

Tags: Java-9

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap