Tuesday, 16 May 2017

Java 7 features

JDK 1.7 (Java SE 7, Java 7) code named as Dolphin was released on July 28, 2011


Features of Java 1.7

* Switch statement with string expression.
* Underscore between digits in numeric literals 
* Handling multiple exceptions in the single catch statement.
* Try with resources statement
* Automatic type interface in generic object 
* static block


* Switch statement with string expression:
   Earlier java 1.7, Switch accept only int values and convertible int values.
   From java 1.7, Switch statement accept string expressions.

                String str = "java";
switch (str) {
case "java":
System.out.println("java");
break;
case "example":
System.out.println("example");
break;

default:
System.out.println("Default");
break;
}

* Underscore between digits in numeric literals .
   * You can place an underscore between number literals.
   * Used to increase the readability of number values.
   * You can place an underscore between thousands, lakhs, etc.    
   * An underscore cannot be first and last of number literals.
  
   int amount = 12_34_567; 
   System.out.println(amount);

* Handling multiple exceptions in the single catch statement.
  * Before java 1.7, we need to write a catch statement for each exception.
  * Now, we can handle multiple exceptions in the single catch statement.
  * We can add multiple exceptions divided my ( | ) pipe symbols.

     String[] str = null;
     try {
   System.out.println(str[0]);
   } catch (NullPointerException | ArithmeticException e) {
       // TODO: handle exception
e.printStackTrace();
  }

* Try with resources statement
   * With java 1.7, we don't need to use finally to close the resources in the 
      try block.
   * In java 1.7,  Its will close the resources when the try block completed 
      the execution.

      try(FileReader reader = new FileReader("file.txt")){
//do print
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

* Automatic type interface in generic object 
  * In Java 1.7, empty angle braces <> (diamond operator) is used to 
     specify the generic type instead of specifying the exact one.

     List<String> list = new ArrayList<>();
     list.add("Hello");
     list.add("World");

* Static block
 * Earlier java 1.7, no main() method is required to print static method.
 * In Java 1.7, without a main() method cannot call static block.

No comments: