Monday, February 3, 2014

Some new features in Java 7 - Part 2

Improved type inference for generic instance creation

Java 5 and 6:

Map<String, List<String>> retVal = new HashMap<String, List<String>>();

Java 7:

Map<String, List<String>> retVal = new HashMap<>();

Removes redundancy in code.

Precise Rethrow:

If multiple exceptions are caught of different types, and if we need to throw them, the code would look like:

public void method () throws Exception1, Exception2 {
    try {

        //code

    } catch (Exception1 e) {

        //log
        throw e;
    } catch (Excpetion2 ex){

        //log
        throw ex;
    }

}


Java 7:

public void method () throws Exception1, Exception2 {
    try {

        //code

    } catch (Exception e) {

        //log
        throw e;
    }
}

Note:
Throws only the checked exceptions that were thrown by the try block and were not caught in any preceding catch blocks

There are many more like ForkandJoin, new file system API (NIO 2.0) which will be discussed in other articles.

No comments:

Post a Comment