Pages

Monday, November 21, 2016

Java 7 and 8 Important Features



1.    Processing Data with Java SE8 Streams – Java 8



The Java API designers are updating the API with a new abstraction called Stream that lets you process data in a declarative way similar to SQL statements. Furthermore, streams can leverage multi-core architectures without you having to write a single line of multithread code.

     Important capabilities of Java Stream API
  • Stream that lets you process data in a declarative way similar to SQL statements, without doing any computation on the developer's end.
  • Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone. To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and streams can leverage multi-core architectures without you having to write a single line of multithread code.


Basic features of Stream:
  • Sequence of elements: A stream provides an interface to a sequenced set of values of a specific element type. However, streams don’t actually store elements; they are computed on demand.
  • Source: Streams consume from a data-providing source such as collections, arrays, or I/O resources.
  • Aggregate operations: Streams support SQL-like operations and common operations from functional programing languages, such as filter, map, reduce, find, match, and sorted.


2.    Catching Multiple Exceptions in Same Catch Block Using | (pipe) Operator  - Java 7

With java 7 it’s possible to catch multiple exceptions in the same catch block (multi catch).Before java 7, it is difficult to create a common method to eliminate the duplicate code as the variable e has different types.

Normal way of catching Exceptions before java 7 
  try {
    // execute code that may throw 1 of the 3 exceptions below.
  } catch (IOException e) {
      e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }

After adding pipe operator and using multi catch

  try {
    // execute code that may throw 1 of the 2 exceptions below.
  } catch (IOException|SQLException e) {
      e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }

Important features of the multi catch Exception handling 
·         This feature can reduce the code duplication and lessen the temptation to catch overly broad exception
·         If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
·         Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers


3.    The try-with-resources statement - Java 7

Before java 7 managing resources that need to be explicitly closed but with java 7 they introduced a way to close the resources easily with the help of try – with –resources option.

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.

Important features of the try-with-resources statement
·         The try – with – resources statement have the capability of closing all the declared resources at the end of try block.
·         Beauty of try-with-resources option is you can use multiple resources inside try-with-resources block and have them automatically closed.

·         The try – with – resources statement can work with both java build – in classes and java.lang.AutoCloseable interface.


Normal way of using try catch finally blocks before using try - with - resources statement

  try{
     //open file or resources
   }catch(IOException e){
     //handle exception
   }finally{
     //close file or resources
   }


public static void main(String[] args) {
    //classical way of reading file before java 7
  BufferedReader br = null;
  
  try {
   String line;
   br = new BufferedReader(new FileReader("file.txt"));
   
   while ((line = br.readLine())!=null) {
    System.out.println(line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }finally {
   
    try {
     if(br != null){
         br.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   
  }
 }

Java 7 can write the code from the above using try -with - resource construct like below 

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
      String line;
      
      while((line = br.readLine())!= null){
       System.out.println(line);
      }
  } catch (IOException e) {
   e.printStackTrace();
  }

Similarly we can use try - with - resources for closing multiple resources

   try(  FileInputStream     input         = new FileInputStream("file.txt");
            BufferedInputStream bufferedInput = new BufferedInputStream(input)
      ) {

          int data = bufferedInput.read();
          while(data != -1){
              System.out.print((char) data);
      data = bufferedInput.read();
          }
      } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }



4.   Switch Statement Supports Strings - Java 7

As we all know java switch cases are considered as one of the best ways in representing conditional statement. Before java 7 switch statements only support int/Integer, byte/Byte, short/Short and char/Character.

Important features of java switch case String:
·         Switch case String enhanced the code readability by removing chained if-else conditions.
·         Switch case string is case sensitive.
·         As String switch case statement use String.equals() method for comparison there is a chance of occurring NullPointerException.(Need to perform NULL check before proceeding with switch statement)

·         According to the java 7 documentation java compiler generates more efficient byte code for string in switch than chained if – else statements.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class SwitchStatement {
 
 public static void main(String[] args) {
  
  //Java 8 Switch statement feature 
  
  testSwitch("Tuesday"); 
 }

 private static void testSwitch(String key) {
  
  switch (key) {
  case "Sunday":
   System.out.println("Today is Sunday");
   break;
  case "Monday":
   System.out.println("Today is Monday");
   break;
  case "Tuesday":
   System.out.println("Today is Tuesday");
   break;
  default:
   System.out.println("Return from default case");
   break;
  }
  
 }

}


      There are many more features in Java 8 & 7 will discuss them one by one later,until that Happy coding !!!!!

Introduction to Java Collection framework

Hi All, Let’s have a simple idea about java collection framework. Here I’d like to have small introduction about different types of collections and Implementation of List interface in collection.
Let’s discuss why we need java collection framework, Java Collection framework offer ordering, uniqueness, Association between unique keys and value, and much more

Different types of collections and characteristics

·         List (order, indexing )
·         Set(distinct elements )
o   SortedSet (Sorted Set )
    ·         Queue(Order in adding removing FIFO)
o   Deque(FIFO,LIFO behavior – Stack )
    ·         Map (Keys & Value )
o   SortedMap(Key value pairs in certain order )

Implementation of interfaces in collections

Interface and Implementations of different collection types, for an example we can implement both linkedList and ArrayList using List interface in collections. Key point to highlight here is, Interface defines behavior and Implementation defines performance

List Implementation




Array List (Dynamic Array)

       ·         When the characteristic are not sure we normally use arraylist
       ·         Fast in accessing and sorting


Linked List (Doubly linked List)

      ·         Less performance compare to ArrayList in accessing and sorting
      ·         Fast in data manipulation
      ·         Good When need to adding elements to the start(Head) – If we do same thing  in the array list it’s       very expensive as we need to shift all elements to the back
      ·         Good When there are lots of adding or removing operations need to be done

Performance Comparison Chart



Here I wish to share some code implementations that visualized primary utilization of Linked List and Array List