Java 7 New Features

Java 7: Features & Enhancements

1)    Strings in switch

switch (database) {

case “oracle”:

case “sqlserver”:

break;

case “postgres”:

break;

case “mysql”:

break;

default:

}

2)    try-with-resources statement

try (InputStream is = new FileInputStream(new File(“data.txt”))) {

// read file

// …

}

catch (IOException ex) {

// handle this error

–          try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoClosable interface. The AutoClosable interface consists of just one method.

void close() throws Exception {}

3)    Throw statement precisely

public void display(String[] args) throws IOException {

try {

loadFileToDb();

} catch (final Exception ex) {

System.err.print(ex.getMessage());

throw ex;

}

4)    Multiple catch statement

try {

doSomething();

} catch (Exception1 | Exception2 ex) {

printException1();

} catch (Exception3 | Exception4 ex) {

printException2();

 

5)    Binary integral literals

–          We can create numerical literals by adding binary notation prefix “0b”

int no = 0b1010;

System.out.println(“no = ” + no);

Output

no = 10

6)    Underscores in numeric literals

–          We  can include underscores in numeric literals to make them more readable. The underscore is only present in the representation of the literal in Java code, and will not show up when you print the value.

int tenMillion = 10_999_999_0;

System.out.println(“Amount is “ + tenMillion);

Output

109999990

7)    Improved type interface for generic instance creation

–          Java 7 tries to get rid of this redundancy by introducing a left to right type inference. You can now rewrite the same statement by using the <> construct.

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

8)    Advanced new I/O API

– This addition is also known as New I/O API (NIO).

See http://download.java.net/jdk7/docs/api/java/nio/file/Files.html

9)    Watch Service

–          It provides an API that lets you “listen” to a certain type of file system events. Your code gets called automatically when those events occur.

–          See http://download.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html