Saturday, July 4, 2015

Try-with-resources Example in JDK 9

In Java 7 and 8:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// try-with-resources statement of JDK 7 or 8
try (BufferedReader r1 = reader) {
// use buffered reader
} catch (IOException e) {
}
//The resource will be closed even without finally statement
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:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// The JDK 9 way
try (reader) {
// use the reader
}catch (IOException e){
}
//The resource will be closed even without finally statement
This is more concise especially when you need the resource outside the scope of the try block.

Popular Posts

Labels

ad ( 6 ) Amazon ( 44 ) analytics ( 1 ) Answer ( 1 ) API ( 28 ) automation ( 1 ) blog ( 23 ) book ( 2 ) business ( 1 ) career ( 22 ) cdn ( 3 ) centos ( 1 ) cloud ( 150 ) cms ( 1 ) CRM ( 25 ) current ( 19 ) data ( 34 ) database ( 70 ) design patterns ( 19 ) development ( 3 ) document ( 1 ) eCommerce ( 30 ) email ( 95 ) enterprise ( 1 ) ETL ( 2 ) file ( 1 ) framework ( 3 ) git ( 15 ) google ( 199 ) IDE ( 24 ) Integration ( 2 ) interview ( 25 ) Java ( 449 ) Java EE ( 118 ) javascript ( 45 ) Jboss ( 5 ) JPA ( 60 ) JSF ( 48 ) linux ( 342 ) Marketing ( 35 ) micro ( 1 ) Microsoft ( 1 ) mobile ( 49 ) model ( 1 ) MySQL ( 203 ) online money ( 18 ) OOP ( 7 ) open source ( 28 ) performance ( 78 ) php ( 53 ) python ( 46 ) quality ( 7 ) referral ( 3 ) restful ( 23 ) security ( 148 ) SEO ( 22 ) social ( 34 ) software ( 79 ) spam ( 4 ) Spring ( 1 ) SQL ( 24 ) system ( 39 ) testing ( 18 ) tool ( 105 ) UML ( 8 ) virtual ( 10 ) web ( 253 ) web services ( 17 ) WildFly ( 8 ) wordpress ( 14 )