Advertisment

Introducing Java SE 7 aka Project Coin

author-image
PCQ Bureau
New Update

Kunal Jaggi, Author of Programming WebSphere MQ with Java and SCWCD Exam Guide with Java EE 5, McGraw-Hill Education

Advertisment

Project Coin, a Java Community Process (JCP) backed JSR 334 initiative is an effort to make the Java programming language more friendly, productive and easy to code. JSR 334 introduces a few small, but highly useful, language features which are now an integral part of Java SE 7. The significance of JSR 334 is rare in a way because this is the first core Java programming language changes since JDK 5 (project Tiger) was released in 2004. This article is the first in a series of two articles aimed at familiarizing you with some of these

language features.

Snapshot

Price:Advanced Java developers

USP: Learn how to simplify your code with the new Java SE 7

Related articles: Java: The Road Ahead http://ld2.in/3sw


Search engine keywords: Java 7

Handle multiple exceptions with a single catch

Advertisment

If you have used the Java programming language, you might have encountered several scenarios where you need to wrap a method call or a group of statements with a few catch blocks, each block catching a specific exception type (and implicitly its subtype). For example, consider the following code snippet presented in Listing 1 which reads a database row with JDBC calls and writes it into a file on the disk.

Listing 1

BufferedWriter writer = null;

Statement stmt= null;

try

{

writer = new BufferedWriter ( new OutputStreamWriter( fos ));

stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(SELECT_EMPLOYEE);

while ( rs.next() ){

writer.write(rs.getString("EMP_NAME"));

}

}

catch(SQLException ex)

{

Logger.log("Error occurred : "+ ex.getMessage());

//do something with the exception

}

catch ( IOException ex)

{

Logger.log("Error occurred : "+ex.getMessage());

//do something with the exception

}

Advertisment

The above code is cluttered with multiple catch blocks, thus making it difficult to read. Also, we have a common code such as log statement and exception handling code in each catch block, resulting in duplication of codes. One option is to move the exception handling code to a separate method call; still we need to call the method from each catch block. Thanks to JDK 7, we can now combine a series of exception types in a single catch block, separated by the “OR” operator symbol “|”. This is presented in Listing 2 below.

Listing 2

try

{

// Open a writer

// Create a Statement and open ResultSet

// Access the ResultSet

}

catch(SQLException | IOException ex)

{

Logger.log("Error occured : "+ ex.getMessage());

//do something with the exception

}

Advertisment

Care should be taken to confirm that a multi-catch statement should not relate subclasses. According to the Java language specification, the exception alternatives in multi-catch clause must be disjoint; one cannot be a subclass of another. For example, the following code snippet will likely give a compilation error.

Listing 3

BufferedReader reader = null;

try

{

URL webUrl = new URL("http://www.jcp.org");

reader = new BufferedReader(new InputStreamReader(webUrl.openStream()));

// do something with the reader

}

catch ( MalformedURLException | IOException e)

{

e.printStackTrace();

}

Advertisment

Since java.net.MalformedURLException is a subclass of java.io.IOException, trying to combine them in a multi-catch statement will result in a compilation error.

Efficient resource management with auto closure

The default Java garbage collector can only control objects which exist on the heap. This excludes resources controlled and managed by the underlying operating system such as files, database and network connections. For example, while dealing with files, care should be taken to close the IO connection in a finally block to confirm that it's called. When an object is no longer in use we need to explicitly close it to free underlying resources. For example, consider the code in Listing 1 and the code snippet presented in Listing 4 below which can confirm that the JDBC Statement object and file writer are closed properly.

Advertisment

Listing 4

finally{ if( writer != null )

{

try {

writer.close();

}

catch( IOException ex ) {

}

}

if(stmt!=null)

{

try {

stmt.close();

}

catch( SQLException ex ) {

}

}

}

The above code is not only error prone (a developer can forget to close the JDBC Statement or file) but can be difficult to read. With Java SE 7 we can simplify the above code to a great extent. Java SE 7 introduced an effective mechanism to initialize a resource when required and automatically close it when the try block ends; it's called try-with-resources statement. This can be most effectively demonstrated with an example, as shown below in Listing 5.

Advertisment

Listing 5

try ( BufferedWriter writer = new BufferedWriter ( osw ) ){ try( Statement stmt = con.createStatement() ){

ResultSet rs = stmt.executeQuery(SELECT_EMPLOYEE); while ( rs.next() ){ writer.write(rs.getString("EMP_NAME"));

}

}

}

catch(SQLException | IOException ex) {

Logger.log("Error occurred : "+ ex.getMessage()); //do something with the exception

}

In the above code listing we declared, initialized and used a BufferedWriter and a JDBC Statement object. Furthermore, the compiler automatically closes the resources when the try block ends. You don't need to call close() explicitly. You should pay special attention to the resource specified in the try-with-resources statement, it should be subtype of AutoCloseable or a compile-time error occurs. Starting with Java SE 7, AutoCloseable is new interface which helps in auto closure of resources when they're no longer needed. The AutoCloseable interface has just one method- close() which is implemented or extended by several Java classes and interfaces, such as java.io.ObjectInput, java.io.ObjectOutput, java.sql.Connection etc. For a full list please refer to the Java Doc.

Conclusion

Writing an efficient code in Java can now require far less typing. Unlike Java 5 features which took some time to become mainstream, I think Java 7 will soon become a de facto standard in the Java community. Java 7 is a major leap forward in compiler automation, it can answer several long awaited questions from the developer community to make Java much easier to code and help avoid unnecessary boilerplate for simple tasks such as resource closures, catching multiple exceptions in a single catch block, implicit type inference and others. JDK 7 is supported in NetBeans IDE version 7.0.1, IntelliJ IDEA 10.5 and beta support is available for Eclipse. Stay tuned for the next article where we will explore other new features introduced in Java SE 7.

Advertisment