Wednesday, July 13, 2011

Java 7: New Feauters

Attended webcast of launch of Java 7 last week. A number of evolutionary new features are added by project coin to make Java developers life easy. In addition to them but more exciting step has been taken by opening JVM for dynamic languages. Now languages like Javascript, JRuby, Python and many more can dance within JVM. What a confluence of back-enders and front-enders, static lovers and dynamic lovers! Stage is set for a new paradigm in programming world ...

I would love to share some of there here.

1. Hurrrey.... finally String can be used in switch statement.
void printSubjectType(String subject) {
String subjectType;

switch(month) {
case "english": subjectType = "Language"; break;
case "physics": subjectType = "Science"; break;
case "algebra": subjectType = "Mathematics"; break;
...
default: subjectType = "Uknown";
}

System.out.println( subjectType );
}


2. No need to mention types of generic on right hand side while initializing variable.
//Old
Map<String, Integer> monthDays = new HashMap<String, Integer>();

//Java 7
Map<String, Integer> monthDays = new HashMap<>(); // equivalent to new HashMap<String, Integer>();

// few more in Java 7
Map<? extends Number> monthDays = new HashMap<>(); // equivalent to new HashMap<Number>();
List<?> list = new ArrayList<>(); // equivalent to new ArrayList<Object>();


3. Multi catch - specify more than one exception in catch clause.
// Old
try {
new FileImageInputStream(new File("test.txt"));
} catch ( FileNotFoundException e ) {
throw(e);
} catch ( IOException e ) {
throw(e);
}

// Java 7
try {
new FileImageInputStream(new File("test.txt"));
} catch ( FileNotFoundException | IOException e ) {
throw(e);
}

4. try-with-resources - New try clause syntax where resources can be initialized. These resources get automatically closed for sure after completing try block.
//Java 7
try( InputStream in = FileInputStream("src"); OutputStream out = FileOutputStream("dest"); ) {
..........
..........
}
// no need to close in and out in finally block what we generally used to do.


Some more sophisticated features:
1. JVM supports dynamic languages like Javascript, JRuby etc. using invokdynamic and call site features.
2. New file APIs.
3. NIO2 - New IO part two APIs. Support for asynchronous IO has been added.

Ref: http://www.oracle.com/us/corporate/events/java7/index.html