Over a million developers have joined DZone.

A New Try-with-resources Improvement in JDK 9

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

The JEP 213 - Milling Project Coin is a follow up to the Project Coin additions to Java 7. Note, as the JEP states, this isn't a Project Coin 2.0. It's more of an attempt at smoothing the "rough edges" that came along with these additions. Just as a reminder - with the original Project Coin, among other things, we got: 
  • Strings in switch
  • Binary integral literals and underscores in numeric literals
  • Multi-catch and more precise rethrow
  • Improved type inference for generic instance creation (diamond)
  • Try-with-resources statement
  • Simplified varargs method invocation
Try with resources has been a great simplification, especially when working with I/O code. The addition in JDK 9 is an improvement of the standard try-with-resources way of writing code. Previously in Java 7 and 8 we had; 
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Original try-with-resources statement from JDK 7 or 8
try (BufferedReader r1 = reader) {
// use buffered reader
} catch (IOException e) {
// ignoring exceptions because that is how I roll
which works just fine, but we still needed to declare a special variable in the try-with section. The cleaner and simpler way in JDK 9 is now; 
// The JDK 9 way
try (reader) {
// use the reader
}catch (IOException e){
// ignoring exceptions because that is how I roll

This is more "natural" way of writing even though it most use cases we don't need the resource outside the scope of the try block. The restriction is that the reader variable should be effectively final or just final. You can play around with the new way already in the latest JDK 9 snapshot. More info available in Joe Darcy's Oracle Weblog post and the related  JDK bug report. 

 Originally published on https://www.voxxed.com/blog/2015/01/new-try-resources-improvement-jdk-9/

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


Published at DZone with permission of Mite Mitreski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}