Wednesday, March 29, 2017

New Features of Java 7

1. Allow String as Switch parameter
 Strings in switch case now allowed as compared to previous versions where only int was allowed
Ex-
public void testStringInSwitch(String param){
final String JAVA5 = "Java 5";
final String JAVA6 = "Java 6";
switch (param) {
case JAVA5:
  System.out.println(JAVA5);
  break;
case JAVA6:
  System.out.println(JAVA6);
   break;
     }

}

2. Allow binary Literals
  In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary   literals.This feature is very helpful to bit-oriented systems like processors, network protocols and bitmapped hardware device. Early the programmer used to transform from binary to decimal/hexadecimal and vice versa.
public static void main(String[] args) {
 int i=0b0111;
 byte b=(byte) 0b0111;
 long l=(long) 0B0111L;
System.out.println("i="+i);
;System.out.println("b="+b);
System.out.println("l="+l);
}
3. Allow underscore between literals
public void testUnderscoresNumericLiterals() {
int oneMillion_ = 1_000_000; //new
int oneMillion = 1000000;
if (oneMillion_ == oneMillion){
System.out.println(true);
} else{
System.out.println(false);
}

4.Type Inference(diamond operator)
Prior JDK 7, you type more to specify types on both left and right hand side of object creation expression, but now it only needed on left hand side, as shown in below example.

Prior JDK 7
Map<String, List<String>>
employeeRecords = new HashMap<String, List<String>>();
List<Integer> primes = new ArrayList<Integer>();

In JDK 7
Map<String, List<String>> employeeRecords = new HashMap<>();
List<Integer> primes = new ArrayList<>();

5.Automatic Resource Management
Before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly, for example while reading files and streams, we need to close them into finally block, which result in lots of boiler plate and messy code.
Read a File before Java 7
public static void main(String[] args) {
        InputStream fin = null;
        BufferedReader br = null;
        try {
            fin = MyTest.class.getResourceAsStream("info.xml");
            br = new BufferedReader(new InputStreamReader(fin));
            if (br.ready()) {
                String line1 = br.readLine();
                System.out.println(line1);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Info.xml is not found");
        } catch (IOException ex) {
            System.out.println("Can't read the file");
        } finally {
            try {
                if (fin != null) fin.close();
                if (br != null) br.close();
            } catch (IOException ie) {
                System.out.println("Failed to close files");
            }
        }
    }
Read File in Java 7
public static void main(String[] args) {
// watch the highlighted text try block can declare resources that need to be managed.
        try(InputStream fin = MyTest.class.getResourceAsStream("info.xml");
            BufferedReader br = new BufferedReader(new InputStreamReader(fin))){
        if (br.ready()) {
                String line1 = br.readLine();
                System.out.println(line1);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Info.xml is not found");
        } catch (IOException ex) {
            System.out.println("Can't read the file");
        }
    }
}

6. Multi Catch Exceptions:
In JDK 7, a single catch block can handle more than one exception types

Ex:
try {
     ......
catch(ClassNotFoundException|SQLException ex) {
ex.printStackTrace();
 }
just remember that Alternatives in a multi-catch statement cannot be related by sub classing. For example a multi-catch statement like below will throw compile time error :

try {
   ......
} catch (FileNotFoundException | IOException ex) {
 ex.printStackTrace();
 }

7. Java NIO 2.0

Java SE 7 introduced java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system.
It also introduced the Path class which allow you to represent any path in operating system. New File system API complements older one and provides several useful method checking, deleting, copying, and moving files.
for example, now you can check if a file is hidden in Java. You can also create symbolic and hard links from Java code.  JDK 7 new file API is also capable of searching for files using wild cards.
You also get support to watch a directory for changes.

8. More Precise Rethrowing exception 


Before JDK 7, re-throwing an exception was treated as throwing the type of the catch parameter. For example, if your try block can throw ParseException as well as IOException. In order to catch all exceptions and rethrow them, you would have to catch Exception and declare your method as throwing an Exception. This is sort of obscure non-precise throw, because you are throwing a general Exception type (instead of specific ones) and statements calling your method need to catch this general Exception
In Java 7
public void precise() throws ParseException, IOException {
try {
       new FileInputStream("abc.txt").read();
      new SimpleDateFormat("ddMMyyyy").parse("12-03-2014");
    } catch (Exception ex) {
     System.out.println("Caught exception: " + ex.getMessage());
     throw ex;
    }
  }

9. G1 Garbage Collector

JDK 7 introduced a new Garbage Collector known as G1 Garbage Collection, which is short form of garbage first. G1 garbage collector performs clean-up where there is most garbage. To achieve this it split Java heap memory into multiple regions as opposed to 3 regions in the prior to Java 7 version (new, old and permgen space). It's said that G1 is quite predictable and provides greater through put for memory intensive applications.

10.Fork Join Framework:
The fork/join framework is an implementation of the ExecutorService interface that allows you to take advantage of multiple processors available in modern servers.
It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.
As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork join framework is distinct because it uses a work-stealing algorithm, which is very different than producer consumer algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy. 

No comments:

Post a Comment