Java 9: Try-With-Resources Improvements

Try with resources was introduced in Java 7. You can read more about it here Java Try With Resources

In Java 9 many improvements have been done with this feature making it much less verbose and usable.

BufferedReader br1 = new BufferedReader(new FileReader(new File(
				"c:\\downloads\\sample.txt")));
		try (BufferedReader br2 = br1) {
			.......
		}

In the above code though br1 was already declared, we still had to declare variable br2 inside try-resource block which is obviously a redundant code.

In Java 9 this is not required and you can write code like this:

BufferedReader br1 = new BufferedReader(new FileReader(new File(
				"c:\\downloads\\sample.txt")));
		try (br1) {
			.......
		}

So basically in Java SE 9, if we have a resource which is already declared outside the Try-With-Resource Statement as final or effectively final, then we do NOT need to declare a local variable.

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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