Tuesday, October 14, 2014

Java 7 Features

1. Automatic resource management with try-with-resources in java 7 (close() method called by JVM) - no catch or finally required

Try-with-resources (originally known as Automatic Resource Management) is a Project Coin proposal that made its way into recent JDK 7 builds. Traditionally, developers had to manually terminate any resources (files, database connections, etc.) they use in applications. It could be difficult keeping track, and not doing so could lead to problems such as resource leaks that could lead to application failures that are hard to debug and triage. Java 7 will now natively support managing resources.

Example:
The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            System.out.println(coffeeName + ", " + supplierID + ", " +
                               price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
}
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.


2. In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.

Before Java 7 you would write something like this:

try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException e) {
    logger.log(e);

} catch(IOException e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}
As you can see, the two exceptions SQLException and IOException are handled in the same way, but you still have to write two individual catch blocks for them.

In Java 7 you can catch multiple exceptions using the multi catch syntax:

try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException | IOException e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}
Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.


3. we can use string literals in switch statements.

In the JDK 7 release, developers can use a String object in the expression of a switch statement. The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method. Because of this, the comparison of String objects in switch statements is case-sensitive. The Java compiler generates more efficient byte code from switch statements that use String objects than from chained if-then-else statements.


public static void main(String[] args) {
      String data="JAVA 7";
     
      switch(data)
      {
          case "DOT NET":
              System.out.println("lower case");
              break;
          case "JAVA 7":
              System.out.println("upper case");
              break;
          case "java 8":
          System.out.println("java");
          break;
           default:
                  System.out.println("Otherthan java");
         }
  }

Output : upper case

4. The Diamond Operator

The Diamond Operator reduces some of Java's verbosity surrounding generics by having the compiler infer parameter types for constructors of generic classes. The original proposal for adding the Diamond Operator to the Java language was made in February 2009 and includes this simple example:

For example, consider the following assignment statement:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
This is rather lengthy, so it can be replaced with this:
Map<String, List<String>> anagrams = new HashMap<>();






























3 comments :

  1. Good collection on java 7 features

    ReplyDelete
    Replies
    1. Hi, Thanks for the comments. I have provided the features which are frequently used and should be known to a basic java developer. Many other features will be incorporated on need basis and if any one is more interested on java 7 features

      Delete