Exploring Java 7 : Try-with-resources

Try-with-Resource is new featured added in Java 7. Personally, I like this feature very much, as it helps to reduce a lot of boiler plate code.

Consider a scenario, where we have to release a system resource, like JDBC Connection or File Stream. Prior to Java 7, it meant that developer has to write a lot of boiler plate code to release that resource. In order to ensure releasing of resource in all the situations, one has to use finally block as well for exception cases. Consider following example, written with Java 6:

String readFirstLine(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null)
    br.close();
  }
 }
Clearly, one has to write almost 4-5 lines for closing each resource. Now, what Java 7 did is that it made the process of closing resource automatic.

In Java 7, a resource is defined as "An object of type java.lang.AutoCloseable.". This AutoCloseable interface has a single method close() and this method is invoked automatically when a resource is used with try block. See below example:
String readFirst(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }

Impressive!!! Isn't it? We have reduced boiler plate code drastically and there is no scope of accidentally forgetting to close a resource. All resource will be freed automatically.

Few points to remember:
  • A resource must be declared in parenthesis, immediately after try block.
  • A Try-with-Resource can have catch and finally blocks, just as with try block.
  • There can be multiple resources in a single Try-with-Resource block
  • public void readEmployees(Connection con){
      String sql = "Select * from Employee";
      try (Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql)){
       //Work with Statement and ResultSet   
      } catch (SQLException sqe) {
       sqe.printStackTrace();
      }
     }
  • In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration

Interface or Abstract Class

What is the difference between an Abstract Class and an Interface?
Well, isn't it an interesting question or for few, a foolish question?

For a number of Java newbies, the only difference between two is, "You can't have method body in Interface.". Well, I would say that it is technically (Implementation vise) correct, but doesn't reflect the concept.

Abstract Class
An abstract class, is the most generalized form of an Entity hierarchy (In Java, a Class is an entity), such that it doesn't represent a real entity on its own, but provides a basis on which real entities can be build within that hierarchy. An abstract class provides a default behavior and also provide abstract behavior (Operations that must be override by the real classes).

Interface
An interface, on the other hand is a contract that states that you have to agree to provide following operations if you agree to abide by me, i.e. an entity that agrees to abide by the contract of interface, will have to provide the behavior (operations) declared in interface.

Interface or Abstract Class
Next question is when to use abstract class and when use an Interface? Though it many a depends on requirements as well, but I follow a thumb rule,
  • If I have to build a class hierarchy, I should consider generalization. Many a time I will reach to most crude form of generalization, i.e. at an abstract level. I would declare abstract methods and will also define common behavior for few of the methods. This would be my abstract class.
  • On the other hand, if I want to expose a particular behavior to the client, then I would define an interface. 

Further, I would suggest that one should go through different Java APIs, and spend some time understanding when and why they used interface or abstract class. Java APIs are excellent source for learning on building design blocks for any OOPs language.