Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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










Tuesday, July 5, 2016

Does Java pass by reference or pass by value?


Hi All, Once upon a time I was in front of an interview panel. Interview panel consist with two guys and one of them asked “Does Java pass by reference or pass by value”, from that day onwards it becomes a nightmare for me. Today I am gonna get ride from it.

I search for an answer here and there, I’m really tired of searching ….I found some articles which says “primitives are passed by value, objects are passed by reference”; this statement is partially incorrect. There is no doubt in “primitives are pass by value”. Problem arise when we start to think about object passing.

Before going in-depth of this discussion, let’s separately discuss the meanings of pass-by-value and pass-by-reference meanings. Below I mention the best description I found on it from Scott Stanchfield’s article.

Pass-by-value


The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.

Pass-by-reference


The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.

Now the time to clear our mess Objects are passed by reference A correct way of expressing that in java is “Object references are passed by value”
Here I’d like to share simple and popular example to have better understanding about the above context





Let’s add something more.
When you pass aDog to the foo() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Below figure shows two references pointing to the same object after Java passes an object to a method.




Java copies and passes there reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects.

Our final conclusion is everything in java is primitives are passed by value, objects




I’d like to share the references that I have used while writing this document






Monday, October 26, 2015

Object Oriented Programming in Java

Hi friends, really sorry for not for posting anything for long time (around 2 months). So today we gonna have simple discussion on object oriented programming principles J



          1.     Inheritance
           2.     Encapsulation
           3.     Polymorphism
           4.     Abstraction

In object oriented programming we learn that class is a blueprint that describe the behavior and the state of an object. Let’s clarify what does it mean by blueprint and how it applicable in this context.



Here the attributes of the phone shows the state of the phone & functions (in java methods) express the behavior of the phone

Here you can see the relationship between class and its objects.
·        HTC Desire 820
·        Microsoft Lumia 535
·         Galaxy S6 edge

     are objects of Phone Class.If these code segments are not clear I will post both the github repo link & slideshare link where you can download the project & the presentation.






As we discuss earlier here you can see the four main features of object oriented programming. Let’s discuss each of these feature separately with examples.

In programming we can define encapsulation is kind of blackbox .Before learning about Encapsulation it will be very useful if you can Watch this video 




Communicating with encapsulated area is only possible through messages (getter & setter methods)











Word CUT get different meanings according to the place it use.
  • For a medical surgeon “cut” leads to do an operation.
  • For an actor “cut” means to stop his /her acting 

Also same way here we can ask for a “phone“ to perform different actions