Java SE 9 : Improved try-with-resources statements

In java 7 or 8 if a resource is already declared outside the try-with-resources statement, we should re-refer it with local variable. That means we have to declare a new variable in try block. Let us look at the code explaining above argument :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code illustrating try-with-resource
import java.io.*;
  
class Gfg
{
    public static void main(String args[]) throws IOException
    {
          
        File file = new File("/Users/abhishekverma/desktop/hello.txt/");
          
        BufferedReader br = new BufferedReader(new FileReader(file));
  
        // Original try-with-resources statement from JDK 7 or 8
        try(BufferedReader reader = br)
        {
            String st = reader.readLine();
            System.out.println(st);
        }
    }         
}

chevron_right


In Java 9 we are not required to create this local variable. It means, if we have a resource which is already declared outside a try-with-resources statement as final or effectively final, then we do not have to create a local variable referring to the declared resource, that declared resource can be used without any issue. Let us look at java code explaining above argument.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code illustrating improvement made in java 9
// for try-with-resources statements
  
import java.io.*;
  
class Gfg
{
    public static void main(String args[]) throws IOException
    {
          
        File file = new File("/Users/abhishekverma/desktop/hello.txt/");
          
        BufferedReader br = new BufferedReader(new FileReader(file));
          
        // New and improved try-with-resources statement in JDK 9
        try(br)
        {
            String st = br.readLine();
            System.out.println(st);
        }
  
    }         
}

chevron_right


This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.