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










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






Tuesday, March 29, 2016

Introduction to Gradle Build Automation Tool
Hi All, Here I would like to discuss about Gradle Build Automation Tool. Kindly note that this is simple learning plan that I was prepare for myself and I am still reading in this field.

Build Automation

Before discuss about Gradle build tool, I think it will be very helpful to have an understanding about build automation.

What is Build Automation Tool?

Build tools are programs that automate the creation of executable applications from source code (eg. .apk for android app). Building incorporates compiling, linking and packaging the code into a usable or executable form. Basically build automation is the act of scripting or automating a wide variety of tasks that software developers do in their day-to-day activities like:
1.      Compiling source code into binary code.
2.      Packaging that binary code.
3.      Running tests.
4.      Deployment to production systems.

Reason for Using Build Automation Tool

In small projects, developers will often manually invoke the build process. This is not practical for larger projects, where it is very hard to keep track of what needs to be built, in what sequence and what dependencies there are in the building process. Using an automation tool allows the build process to be more consistent.

Available Build Tools

·         For java - Ant,Maven,Gradle.
·         For .NET framework - NAnt
·         c# - MsBuild.

(Credits goes to Ritesh Gune – stack overflow)

Before Comparing

Usually as humans when we get or deal with something we start to compare it with other existing things which has the same capabilities .It will be a greater mess if we have no better understanding about each in individually. So this will be the right time to look at Ant and Maven before discuss about Gradle Build tool.

Introduction to Ant


Apache Ant is the Eldest fellow among modern build tools. Ant uses XML to describe the build process and its dependencies.  Ant made it easy for willing developers to adopt test-driven development, and even Extreme Programming.
One of the primary aims of Ant was to solve Make's portability problems. Ant solves this problem by providing a large amount of built-in functionality that is designed to behave the same on all platforms.

Limitations of Apache Ant

Ant build files, which are written in XML, can be complex and verbose. The complex structure (hierarchical, partly ordered, and pervasively cross-linked) of Ant documents can be a barrier to learning. The build files of large or complex projects can become unmanageably large.

Introduction to Maven


Maven is a project management tool which can used for building and managing any Java-based project. Maven’s primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal.


Mavens Objectives

Making the build process easy
While using Maven doesn’t eliminate the need to know about the underlying mechanisms, Maven does provide a lot of shielding from the details.
Providing quality project information
Maven provides plenty of useful project information that is in part taken from your POM and in part generated from your project’s sources. For example, Maven can provide:
·         Change log document created directly from source control
·         Cross referenced sources
·         Mailing lists
·         Dependency list
·         Unit test reports including coverage

As Maven improves the information set provided will improve, all of which will be transparent to users of Maven.Other products can also provide Maven plugins to allow their set of project information alongside some of the standard information given by Maven, all still based on the POM.
Providing guidelines for best practices development
Maven aims to gather current principles for best practices development, and make it easy to guide a project in that direction.
For example, specification, execution, and reporting of unit tests are part of the normal build cycle using Maven. Current unit testing best practices were used as guidelines:
·         Keeping your test source code in a separate, but parallel source tree
·         Using test case naming conventions to locate and execute tests
·         Have test cases setup their environment and don’t rely on customizing the build for test preparation.
Maven also aims to assist in project workflow such as release management and issue tracking.
Maven also suggests some guidelines on how to layout your project’s directory structure so that once you learn the layout you can easily navigate any other project that uses Maven and the same defaults.
Allowing transparent migration to new features
Maven provides an easy way for Maven clients to update their installations so that they can take advantage of any changes that been made to Maven itself.
Installation of new or updated plugins from third parties or Maven itself has been made trivial for this reason.

Comparison table for major advantages/disadvantages - Maven vs Ant.


Maven
Ant
Description of project
Development of a build script per project
Invocation of defined goals (targets)
Invocation of project specific targets
Project knowledge
"Just" the build process
build lifecycle, standard project layout
too complex scripts
reusable plugins, repositories
scripts are not reusable
moving fast forward
development are slowed down
(Table credit goes to - http://www.javafaq.nu/java-article1168.html)

Brief Introduction to Gradle


Gradle is a build automation tool which is used for building, Testing, Publishing deployments, Packaging Software. Build automation means helping developers to complete their software development without unnecessary efforts for
·         Directory preparation
·         Compilation
·         Packaging
·         Managing dependencies

When we use automated build tool it manage the required libraries and dependencies. Simply gradle is a build automation tool which has
·         A very flexible general purpose build tool like Ant.
·         Switchable, build-by-convention frameworks like Maven.
·         Very powerful support for multi-project builds.
·         Very powerful dependency management (based on Apache Ivy).
·         Full support for your existing Maven or Ivy repository infrastructure.
·         Support for transitive dependency management without the need for remote repositories or pom.xml and ivy.xml files.
·         Ant tasks and builds as first class citizens.
·         Groovy build scripts.
·         A rich domain model for describing your build.

Comparison between Three Build Tools

  • Ant has the issue of lack of conventions, because of that need to specify everything. Simply it’s not readable
  • Maven has many conventions. Maven POM allows us to mention the dependency and it will resolve the dependency when it needed without developer interaction (No more struggling with jars).
  • Maven written in xml and maintainable than ant.

If you are new to this probably you may confused with the meaning of “Gradle is declarative and uses build-by-convention”. What does this mean? Before going into the depth of the meaning let’s see the difference of imperative programming and declarative programming.
  • With imperative programming, you tell the compiler what you want to happen, step by step
  • With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step)
Using gradle we can achieve declarative build. Declarative build is the goal of the gradle. In declarative approach we no need to deal with steps (No lots of codes in build file).It’s much readable than past once. It helps to overcome the difficulty in maintaining, accessing and testing.
Now let’s dig down into our problem.

Build-by-convention
Build by convention is the idea that if you follow the default conventions, then your builds will be much simpler. So while you can change the source directory, you don't need to explicitly specify the source directory. Gradle comes with logical defaults. This is also called convention over configuration.
In java plugin there are conventions like source must be in src/main/java,tests must be in src/main/test, resources in src/main/resources, ready jars in build/libs and so on. However, Gradle do not oblige you to use these conventions and you can change them if you want.

Declarative 
The idea behind declarative is that you don't have to work on the task level, implementing/declaring/configuring all tasks and their dependencies yourself, but can work on a higher, more declarative level. You just say "this is a Java project" (apply plugin: "java"), "here is my binary repository" (repositories {...}), "here are my sources" (sourceSets {...}), "these are my dependencies" (dependencies {...}). Based on this declarative information, Gradle will then figure out which tasks are required, what their dependencies are, and how they need to be configured.
The idea of the build being declarative is that you don't need to specify every step that needs to be done. You don't say "do step 1, do step 2, etc". You define the plugins (or tasks) that need to be applied and gradle then builds a task execution graph and figures out what order to execute things in.
Gradle has three distinct build phases

  1. Initialization
Gradle supports single and multi-project builds. During the initialization phase, Gradle determines which projects are going to take part in the build, and creates a Project instance for each of these projects.

  1. Configuration
During this phase the project objects are configured. The build scripts of all projects which are part of the build are executed. Gradle 1.4 introduced an incubating opt-in feature called configuration on demand. In this mode, Gradle configures only relevant projects

  1. Execution
Gradle determines the subset of the tasks, created and configured during the configuration phase, to be executed. The subset is determined by the task name arguments passed to the gradle command and the current directory. Gradle then executes each of the selected tasks.

Introduction to Groovy


When we discuss about gradle, the discussion may incomplete if we forget to mention a word about Groovy. Groovy is a JVM language which has the OOP capabilities .In Groovy website they have mention that







Apache Groovy is a powerfuloptionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.”


Basic Gradle Commands


By typing gradle  – – help  in cmd you can see the list of commands that you can use in command line .There are list of preconfigured properties in gradle which is configured to make your work easy. You can view those properties by typing gradle  --properties in your command window . gradle task is another popular gradle command which we will use very often and will discuss it later in this post.

build.gradle File


This is the name that they use for build file in gradle.Using build.gradle file we can give instructions to the Gradle.As developers we heavily work with this file.This is the place where you can find Groovy Scripts.We can specify different tasks inside this file.When we specify tasks in build.gradle file gradle build system will execute those tasks for us.

Gradle Installation


 We can install gradle in different ways
  1. From web
  2. Using Groovy environment manager
After downloading gradle from http://gradle.org/ website extract it in your machine and set your environment variable path to the bin folder of the extracted gradle.Now you need to check whether environment variables are properly set and gradle is working on your machine. Type gradle in your cmd

Working with Tasks in Gradle


Now you can select any preferred location in your machine and create build file with .gradle extension. Every Gradle project contains a build file called build.gradle. Which contains the tasks (plugins and dependencies)
Fundamental activity in Gradle is task .Now you may think what is the meaning of a task in gradle is. Simply it’s a code that gradle execute .Each task has its own lifecycle with initializing, execution and configuring phases. Task will also contains properties and actions (first and last)
Groovy is a JVM language and its Object Oriented .In gradle build script top-level object is called as project. There is a one-to-one relationship between a Project and a build.gradle file. During build initialization, Gradle assembles a Project object for each project which is to participate in the build.If you need to learn more about project visit https://docs.gradle.org/current/dsl/org.gradle.api.Project.html
project.task("TaskA")  

Let’s see some different ways of declaring task inside build.gradle

You can use any of these methods to declare a task inside build file by typing gradle tasks in the cmd (should be inside the directory where you place your build.gradle) you can get the declared task list.

Above we have discussed that task can have properties and actions .Here I have write some task which contains actions and properties.

To view all task you can use gradle tasks & if you need to execute any task alone you can use gradle <task_name>





We have lot more to discuss about Gradle .It seems we need to discuss those in another post .I have some reference suggestions for you
·         http://www.groovy-lang.org/
Happy build :D