Tuesday, March 4, 2014

Java 7 new features

1. Java 7 Switch String Support
Until the previous version, Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type. i.e Prior to Java 7, it supported variables and expressions which resolved into int, byte, short or char only (OR) it supported Enums. But now, Java 7 has added supporting String types for Switch statement Case values and with this feature, it will surely save a lot of complex if-else structures and improve the overall code readability. Here is a self explanatory example of Switch with Strings in action. We simply accept the String input and print the corresponding matching case
package com.java7.features;

import java.util.Scanner;

public class Java7SwitchDemo {
    public static void main(String[] args) {
 System.out.println(" Sachin\n Dhoni\n Kumble\n ");
 Scanner sc = new Scanner(System.in);
 String cricketer = sc.nextLine();
 System.out.println("\n");
 switch (cricketer.toUpperCase()) {
    case "SACHIN":
         System.out.println("You like batting");
         break;
    case "DHONI":
         System.out.println("You like Wicket keeping");
  break;
    case "KUMBLE":
         System.out.println("You like bowling");
                break;
    default:
  System.out.println("You dont like cricket");
 }
  
   }
}


2. Java 7 Try with resources
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. In the below example, the resources declared in the try-with-resources statement are: Connection, Statement and ResultSet from java.sql package. The declaration statement appears within parentheses immediately after the try keyword. The class Connection, Statement and ResultSet, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because these instances are declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method throwing an SQLException). Prior to Java SE 7, you have to use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.
package com.java7.features;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TryWithResources {
   public static void main(String[] args) throws SQLException {
      try(Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
 Statement stmt = con.createStatement();
 ResultSet rs = stmt.executeQuery("select * from dept")) 
 {
      while(rs.next()) {
      System.out.println("Employee Name : "+rs.getString("deptno"));
      System.out.println("Salary : "+rs.getString("dnmae"));
    }
       };
    }
}
Note: It should be noted that the resources will be closed in the reverse order of their declaration i.e in the above example, first the ResultSet will be closed followed by Statement interface and then finally, the Connection will get closed.

3. Java 7 Multi catch block
In the pre Java 7 world, you would handle exceptions by writing separate catch blocks for different types of exceptions that can occur in the try block. In case of related exception, the derived class exception are listed above the base class exception, e.g. FileNotFoundException should be listed above IOException since FileNotFoundException is derived from the IOException. Java 7 multi catch block provides you the flexibility to combine such catch blocks, provided you have similar code to handle these exceptions and Java 7 provides this by the help of the pipe (|) operator which seperates the different exceptions. Lets have a look at the below example where we handle all the exceptions thrown by the try block in a single catch block, but still specifying the type of exceptions we are handling:
package com.java7.features;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class Java7MultiCatch {
  public static void main(String[] args) {
     try {
       BufferedReader br = new BufferedReader(new FileReader(
          "c:/test.txt"));
       Class.forName("oracle.jdbc.driver.OracleDriver");
       Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1565:myDB");
        } catch (IOException | ClassNotFoundException | SQLException e) {
            System.out.println("Multi catch block here!");
            e.printStackTrace();
        }
 
    }
}

Note: It should be noted that when we use multi catch block, we cannot place the exceptions in a hierarchy seperated by the pipe (|) operator like catch(FileNotFoundException | IOException e) because then the compiler will generate an error that the 'subclass exception (i.e FileNotFoundException) is already caught by an alternative superclass exception (i.e IOException)' which seems to be valid where there is a single exception's stack trace is something we will be dealing with.

Java 7 also introduced new support for File IO operations i.e it introduced Java NIO 2.0 API where the most important concepts are : Path Class and the File Change Notifications using Watch service. I will post it as a seperate entry in the blog soon. Till then, Enjoy reading more about the exciting features of Java 7 :)

2 comments:

  1. Good one, Nice to see the new features listed out with examples...

    ReplyDelete
  2. Well articulated and well explained with simple examples. Looking forward for the next post on NIO package.

    ReplyDelete