Showing posts with label Java 7. Show all posts
Showing posts with label Java 7. Show all posts

Sunday, November 17, 2013

try-with-resources, introduced from Java SE 7

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

 static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }


Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

 static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null) br.close();
  }
 }


reference: http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

Sunday, August 4, 2013

Java 7 Pocket Guide, 2nd Edition


When you need quick answers for developing or debugging Java programs, this pocket guide provides a handy reference to the standard features of the Java programming language and its platform. You’ll find helpful programming examples, tables, figures, and lists, as well as supplemental information about topics including the Java Scripting API, third-party tools, and the basics of the Unified Modeling Language (UML).
Updated for new features through Java SE 7, this little book is an ideal companion, whether you’re in the office, in the lab, or on the road.
  • Quickly find Java language details, such as naming conventions, fundamental types, and object-oriented programming elements
  • Get details on the Java SE 7 platform, including development basics, memory management, concurrency, and generics
  • Browse through basic information on NIO 2.0, the G1 Garbage Collector, and Project Coin (JSR-334) features
  • Get supplemental references to development, CM, and test tools; libraries; IDEs; and Java-related scripting languages
  • Find information to help you prepare for the Oracle Certified Associate Java SE 7 Programmer I exam