Srikanth Technologies

Features of Java 7.0

As Java 7.0 is ready to be released (on July 7th,2011), I would like to post a couple of blogs with the new features of Java 7.0. There are additions to language as well as library. I will focus on both language enhancements and library enhancements in the forth coming blogs.

In this blog, I am focusing on new features added to Java 7.0 under the project - Project Coin, which contains small enhancements related to Java language.

Support for Strings in Switch

Starting from Java 7, switch statement supports strings. It means you can have a string as the expression in switch and compare it with strings given in case statements.

Here is an example for a switch with String.

import java.util.Scanner;

// switch supports strings 
public class StringSwitch {
    public static void main(String[] args) {
        
          Scanner s= new Scanner(System.in);
          System.out.print("Enter the name of programming language you use : ");
          String lang = s.nextLine();   // read a line from keyboard
          switch(lang) {
              case "java" : 
                  System.out.println("Java Programmer"); break;
              case "c#" : 
                  System.out.println(".Net Programmer"); break;
              case "c++" : 
                  System.out.println("C++ Programmer"); break;
              default:
                  System.out.println("Programmer"); break;
          }
    }
}

Improved Type Inference for Generic Instance Creation

In Java 6.0, when we create an object of a class with parameterized types, we need to specify the type both in the declaration (left of =) and also in the call to constructor (right of =).

For example here is an example in Java 6.0.


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

The types to be used on the right of HashMap are evident from the declaration. So it is redundant but needed in Java 6.0.

Starting from Java 7.0, you are allowed to omit type information at the time of creating an object of class with generics if the information can be inferred from declaration. That means the following is enough in Java 7.0 for the declaration above in Java 6.0


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

The above statement simplifies the declaration by removing redundancy related to specifying types in generic declarations.

Automatic Resource Management

A resource is an object that is to be closed manually. An example is an OutputStream, a Connection or a Socket. Automatic resource management statement is a form of the try statement that declares one or more resources. The scope of these resource declarations is limited to the try statement. When the try statement completes, whether normally or abruptly, all of its resources are closed automatically. For example the following is the code we have in Java 6.0 to open and close a stream.

        FileOutputStream fos = new FileOutputStream(path);
        try {
            // code to process fos
        } 
        catch(Exception ex) {
            System.out.println(ex);
        }
        finally {
           fos.close();
        }
Here is the modified version that uses Automatic Resource Management of Java 7.0.


       try (FileOutputStream fos = new FileOutputStream(path))
        {
            // code to process fos
        }
        catch(Exception ex) {
            System.out.println(ex);
        }

Binary integral literals and underscores in numeric literals

Binary integer literals are just like hexadecimal integer literals except that binary digits are used instead of hexadecimal digits. Binary literals are prefixed by "0b" rather than "0x". Here is an example for binary literal.

In numeric literals, underscores are allowed as separators between digits. This applies to literals in binary, octal, hexadecimal, or decimal and applies to floating-point literals also.


        int n = 0b10000000;
        System.out.println(n);  // prints 128

        
        int n2 =  121_31_23_232;   // integer literal with underscores 
        int n3 =  0xff_dd;   // hexa literal with underscores 
        System.out.println(n2);
        System.out.println(n3);

Multi-catch and more precise rethrow

Java 7.0 allows a single catch block to handle two or more exceptions by listing exception types separated by | (or) symbol. This allows one catch block to handle multiple exceptions and take the same action for multiple exceptions.

         try {
            int v = Integer.parseInt(num);
            int result = 100 / v;
            System.out.println(result);
        }
        catch(NumberFormatException | ArithmeticException ex ) {  // multi-catch 
            System.out.println("Not a valid number or zero");
        }

More precise rethrow

If an exception parameter is not modified and if it is rethrown inside the catch block, the compiler applies a more precise analysis to determine the type of what can be thrown.

For example consider the following example in Java 6.0.


class Ex1 extends Exception { }
class Ex2 extends Exception { }

public class RethrowException {

    public void m1(int v)  throws Ex1 , Ex2 {
        try {
            if (v < 0) {
                throw new Ex1();
            } 
            else
               if ( v > 100 ) {
                   throw new Ex2();
               }
            // process 
        } 
        catch (Exception ex) {
            throw ex;   //   unreported exception java.lang.Exception; must be caught or declared to be thrown
        }
    }
}
In the above code, throw ex; will result in error as ex is of type Exception and method has only Ex1 and Ex2 in throws clause. Exception is much more general than Ex1 and Ex2, so Java doesn't allow us to throw ex, which is declared as Exception.

But the same code without any change will compile in Java 7.0 as Java applies more precise analysis to determine the type of exception being thrown. Java 7 understands only two possible exceptions (Ex1 and Ex2) can be thrown from try block. So, it allows ex to be rethrown though ex is declared as Exception.

Here are some other links that are related to Java 7.0 features.

Objects class in Java 7.0

Path class and Files class