Java 7 features – Exception Handling

Java 7 language has introduced features like Usage of Stirings in Switch case, and improving the exception
handling . It introduced multi catch block

Prior to java 7, if we want to handle multiple exceptions in single catch block is not possible, but we can achieve this using multiple catch block where each catch block used to catch single exception.
Let us see the example of multi catch exception handling in java 7

Handling multiple exceptions in catch block example prior 7

For example, prior to java 7, if we want to catch multiple exceptions, thrown by try block, we need to write a separate catch block for each exception type as shown below.
 // possible code throwing exception 
     }catch(IllegalArgumentException iae){
 //catch  IllegalArgumentException and print error message
     }catch(Exception iae){
 //catch  Exception and prints error message
Java 7 introduced multiple exceptions are handled in single catch block
Handling multiple exceptions example in java 7
Java 7 has introduced single cach block for handling multiple exceptions thus reduce code of catch blocks
Below example
   // possible code throwing exception
catch(IllegalArgumentException iae|Exception e) {
In the above code, IllegalArgumentException and Exceptions are defined in same catch block with separator pipe | symbol

Advantages of Multi catch exceptions in Single catch block:-

1. Simplify the coding
2. Decrease code duplicate
3. Reduces catch blocks

That’s my understanding on multi catch block in java 7 language

Java Connection Pooling

Usually applications are hosted on application server, and talk to database using database connection. data
base connection is plain HTTP socket connection to database machine.
Whenever request comes to application, application create a plain socket connection to database, once the request is completed, connection is timeout/closed, so like this for every request, connection is established and performances of application is decreased.So connection is expensive operation, so for every request, creating connection and closing connection is expensive operation. creating and closing connections need to be handled by applications.
To improve the performance of connections mechanism, connection pool is introduced.

Connection pool is a mechanism/concept used by software applications to connect to backend databases with a pre created group connections and reuses the connections whenever required,
Once a request is completed, connections are placed in connection pool

Connection pool is pool of group of pre created connections managed by application server or webserver,

Advantages of Connection Pool

Reduce network calls, thus improve network latency
Improve the application performances by reusing the connections
No need of opening or closing connections as group of connections already in pool and reuse and placed in or out from pool.

Disadvantages of Connection Pool

Need to do configure connection pooling carefully, otherwise database reject/close connections.
Connections are like a resource and there might be resource memory leakage issues

How to create Connection Pooling in java

Below are the examples to create various ways to create a connection pool.
Connection Pool can be implemented in various ways by using Custom java code connection pooling using LIFO stacks or FIFO Queues or different frameworks provided by apache and others.
Connection pool can be created in either in Standalone or web container/application Servers like jboss, tomcat , weblogic and websphere.

JDBC Connection Pooling example

Connection pool can also be created usind jdbc using JNDI name or Datasource.
JNDI name is a name configured mapped to connection pools using websphere, weblogic
Datasource is interface on which implementation can be done by different vendors like apache DBCP and c3po

Connection Pool settings:-

For any connection pool, Below number of parameters are required. For having better performance in Production systems, settings need to be tuned.

Total number of connections in Connection Pool:-This parameter specifies the total number of connection to be created at start up. Basically in web application, these connections are created at application start up and destroyed when application stops.

Maximum Connections :- tells maximum connections to be created in connection pool

Minimum connections: - specifies minimum connection to be create a pool

Connection Increment: - if total request are more than maximum connections, container increment the connection count

Connection pool Idle timeout :- if connection is established and idle for some time, then container return that connection to pool, later other request can be reuse it. This is basically to free the database connection resource.

Apache DBCP Connection pool tutorial:-

Apache DBCP is database connection pooling concept to create/manage group of connections. This can be used to create a java database connection pool to improve the performance of an java applications. Apache tomcat is internally using DBCP connection pool framework

connection pool using Apache DBCP with example

Datasource object is required for getting Connection object.
To get Datasource object, we need to create a following code
import java.sql.*;
import org.apache.commons.dbcp.*;

public class C3POPConnectionExample {
 public static void main(String args[]) throws Exception {
  BasicDataSource dataSource = new BasicDataSource();
  Connection con = dataSource.getConnection();
  System.out.println("Connection Object information : " + con);

To execute/compile the above dbcp connection pool example, dbcp jar should be in classpath

Java C3PO connection pool

C3PO connection pool is one of powerful and stable open source connection pool, performance is also good compared to apache dbcp.

Below is the example for C4PO code. Before that c3po jar should be in classpath.

import java.sql.*;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBCPConnectionExample {
 public static void main(String args[]) throws Exception {
  ComboPooledDataSource connectionPoolDatasource = new ComboPooledDataSource();
  Connection con = connectionPoolDatasource.getConnection();
  System.out.println("Connection Object information : " + con);

that's it my learnings/understanding on connection pooling in java.

Please click +1 if you like this post.

Basic Cat command examples in Linux/Unix

Cat command is simple command used by every Unix/Linux user. It is one of frequently used command in Linux/Unix Systems.Cat command works on bash, and powershell and shell options.
Cat command behaves different based on the different types of usage.

By using cat command, we can do the following functionalities

1. Read files using cat command
2. Create files Using cat command
3. Copy files content using cat command.

Cant command works unix,linux as well as ubuntu terminals

Cat command Syntax

Cat (options) (one or more file name)

Let us see the various cat command examples as below.

Read or view file using cat command with examples in Linux/Unix

This is simple command to read the contents of file and output the file content to Standard output like console
$cat cloud.txt

This is test file contains test content.
If it is small file, we can view it using cat command, but file size is large we can use more or less with pipe options in cat command.

How to create a file using Cat command in Unix

Cat command is a basic command to create files. To create a file demo.txt
$ cat >demo.txt
This is test file contains
test content.
Once the above command is entered, new demo.txt file is created and console waits from user to type input and whatever data typed by user is placed in file.> symbol specifies that data to placed in a file typed by a user. You need to type CTRL with typing D to save data to file and exit from console.

How to merge files using cat command in Linux/Unix

Cat command also used to merge different files and create a new file
$ cat file1 file2 > output.txt

First file1 data is copied to output.txt and next file2 data is copied to end of file1’s data.

How to view the line numbers of each line using cat command

In java programs, if any error happens, Error/Exception thrown with print statck trace which will give filename as well as line number where exception is occurred. In that case, to view the java code with line numbers, we can use cat command with option –n
$ cat –n cloud.txt
1 This is test file contains
2 test content.

Append/concatenate data to existing file using cat command

$cat >>cloud.txt
New data is appending to existing file
We have to press CTRL+D option to save/append the new data to existing data in a file

How to view file with showing spaces, tabs using cat command with examples.

In any text Editors, we have option to be enabled to show spaces and tabs codes

Cat has also has the option to view spaces and tabs and end of lines using option –T
$ cat –T filename

Cat command options

Basic cat command has different options, can be used with all flavors of linux like AIX

-T output spaces, tabs and End of lines characters in the file
-s suppress the multiple blank lines
-n output number on each line of file

That’s it from usage of cat command in daily life of software development.

Please click +1 if you like this post.

String in switch case tutorials

Java 7 language has introduced using string in switch case. Prior to java 7 version, Switch case allows only Integer, byte, short, char variables and enumeration values only. Support of String is not a great language
feature but a handy for developers to use strings directly in switch case and simplify the developers in readability.
This post is my first post on java 7 features; I will do more posting on java 7 features in coming weeks.
Let us see the following code

public class SwitchWithStringsDemo {
    public static void main(String[] args) {
        int days = 1;
        String s="one";
        String numberValue;
        switch (s) {
            case 1:  numberValue = "ONE";
            case 2:  numberValue = "TWO";
            case 3:  numberValue = "THREE";
            default: numberValue = "Invalid number";
What will happen if we compose the above program in eclipse/net beans using java 1.7 version, so let us see the output of the above program in command line too

Eclipse error for usage of String in switch case below jdk 1.7 version

If we use directly use String in switch case, eclipse /net beans code editor throws following error.
Can not switch on a value of type string for source level below 1.7. Only convertible int values or enum constants are permitted.

Compile time error with using String in switch case

When java program using strings in switch is compiled with below java7 version, below error is thrown on command line.
Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – strings in switch are not supported in -source 1.6
(use -source 7 or higher to enable strings in switch)

Advantages of Using String in Switch case feature in java 7.

Alternative to Switch case is if else statements but it is not that much readable as well as confusing developer in terms of more lines of code and cyclomatic complexity is increased. Cyclomatic complexity is method to identify the complexity of code
We have different alternative methods for using in Strings in switch case

Alternative to strings in Switch case using if else below java 1.7.

This is not an exact alternative to String usage in Switch case, but an alternative to switch case.
public class IfElseDemo {
 public static void main(String[] args) {
  String value = "ONE";
  if ("ONE".equals(value)) {
   System.out.println("Message One");
  if ("TWO".equals(value)) {
   System.out.println("Message One");
  if ("THREE".equals(value)) {
   System.out.println("Message One");

Alternative to String in Switch case example below jdk 1.7 using enums

Prior to java 7, enum’s can be mapped to switch case and below code specifies the usage of enum.
public class AlternativeToStringSwitch {

 public enum Daily {

 public static void main(String args[]) {

  String str = "ONE";

  switch (Daily.valueOf(str)) {
  case ONE:

  case TWO:

  case THREE:


Example of String in switch case in jdk 1.7 with tutorials

public class SwitchStringDemoDemo {
    public static void main(String[] args) {
        int days = 1;
        String string="one";
        String numberValue;
        switch (string) {
            case "one":  numberValue = "ONE";
            case "two":  numberValue = "TWO";
            case "three":  numberValue = "THREE";
            default: numberValue = "Invalid number";
In java 7, variable of Strings are assigned and can be referenced in Switch case. Case Strings values are constants as like before in jdk6 version.

Null check for Strings in Switch case in java 7

As like other java code, if null is passed as String in Switch case, NullPointerException is thrown.
We have to handle the null checks for strings passed.
Please click +1 if you like this post.

How to Fix/handle java.lang.ArrayIndexOutOfBoundsException errors in java

What is java.lang.ArrayIndexOutOfBoundsException error in java?

This exception is one of the common exceptions in java. Java developers used to get this exception in the projects which gets the data from the database as well as dealing with arrays and array lists.
ArrayIndexOutOfBoundsException is a class in java. lang package which extends IndexOutOfBoundsException, extended by RuntimeException. IndexOutOfBoundsException is runtime exception which occurs at during java execution in java virtual machine. Runtime exceptions might not declare in method signatures unline checked exceptions has to declare in method signature declaration
Java throws ArrayIndexOutOfBoundsException exception when an invalid index is accessed in array.
And the sample exception print stack trace is as follows

Print Stack trace for ArrayIndexOutOfBoundsException error in java?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

Below java program code throws ArrayIndexOutOfBoundsException exception
public class ArrayIndexOutOfBoundsExceptionExample {

public static void main(String[] args) {
 Integer array[] = new Integer[10];
 System.out.println(" array index 0  value " + array[0]);
 System.out.println(" array index 10 value " + array[10]);

Above java code create a Integer array of size 10,
In java ,array ‘s index always start with 0 and last index is 9 Array with index 0 to 9 has the default values Null(Integer object default value). . Accessing array with index out of this range (0 -9) throws this exception.
Executing array[0] executes fine and outputs null, where as array[10] is invalid and index 10 is invalid, so java program throws Array Index Exception.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
 at ArrayIndexOutOfBoundsExceptionExample.main(

How to handle ArrayIndexOutOfBoundsException error in java?

Let us see how to handle/ solve IndexOutOfBoundsException exception types in java

1.       Always check for expected invalid index  in array bounders
Arrays are fixed in size and always start with index 0.  We have to write a conditional check to consider the array elements between 0 to n-1 if array size is n-1
Possibility fix is to  have for loop check for valid ranges
for(int index=0;index<array.length;index++)</pre>

2.      Fix for  Array Index Bounds Exception  as well as IndexOutOfBounds Exception for arraylist
ArrayList also has index based methods like set  and get This exception throws when we are accessing ArrayLlist elements with get method before  adding the elements/objects into arraylist using set method. So make sure that add below check in arraylist or vectors
<pre>if(index >0 || index <= arraylist.size())</pre>

Please click +1 if you like this post.

Top 10 LS command examples in Unix /Linux

Ls is one of the frequently used command in Linux as well as UNIX and it is important to know about this command  Ls command list the names of files or directories in a directory.
ls command sort the files alphabetically and output to standard console. when ls command is executed, Linux server do inode sorting and outputs the files on alphabetically
in Linux files metadata are stored in data structure which includes file owner, file access rights and file type. Each inode is an unique index number in organized file system data structure
ls is  one of the basic command of unix/linux operating system.
ls command works on bash shell as well as Cent OS of unix.

ls command syntax usage
$ls (options) (file name or directory)

ls command syntax is shown above and ls command examples are shown below

How to display content of directory using ls command
bash-3.2$ ls
cloud.txt  directory1

ls command without options displays the files and directories in a current directory

bash-3.2$ ls
cloud.txt  directory1

How to list the inode information using ls command line

$ls -l filename
12345 filename
here 12345 is index number
l without options list the files and in directory

How to list the files and directories in a given path
$ls -l
ls command with option -l list out the long file format information about files and directories

How to list the files based on sorting order modification time.
$ls -t
ls command with option -t displays the recent modified file first and so on

How to list directories using commands
$ls -d 
ls command with option -d outputs list of directories in a given path, but not sub directories

How to print the files without doing sorting ?

$ls -f  or ls -U
ls command do the sort the files alphabetical and outputs it, Suppose In a given directory, if there 500 files, To view all these files, if ls command is supplied without any arguments, server does sorting of this files inode and takes more time in hours, so in this case we need to use ls command with option -f to list the filenames without doing sorting

How to display content of files/directory recursively

to list the files in directories and sub directory or recursive directories
$ ls -R  
How to show hidden files in command line
$ ls -a  or ls -A
ls command with option -a ouputs the normal files as well as hidden files. to differentiate normal file with hidden files, hidden files are always start with '.'
Top 10 Simple examples of Grep Command with explaination in linux
Grep is popular and powerful command in linux and unix operating system. Each developer and QA in software development need to know about grep command usage.
Questions on Grep is asked by almost all interviews for developer/QA role. Every one in Software field must know the Grep Usage and commands
Grep is used to search in file or multiple files for matching keyword or lines. Grep search for a word and return the line in set of one or more files.Grep command can be input to some other command and Grep can be used in variety of ways as follows

Grep Command usage syntax:-
grep 'word' /file/name or /directory/path
Below is the sample file for all grep examples.
$ cat cloud.txt
This tutorial is about grep command in linux and unix usage
Grep is powerful search tool for searching words in set of files
Grep can be used with other linux commands
Grep is so fast compared to other commands in linux systems..

How to search for a word in a file

$ $ grep 'word' cloud.txt
Grep is powerful search tool for searching words in set of files

Keyword ‘word’ searched in in cloud.txt return the matching line which has ‘word’.
By default grep without any options search for files if file name is specified, and directories, not sub directories if directory specified

How to do case insensitive search for a word in a files.

By default Grep command in linux or unix treats each case sensitive word as different.
To do case insensitive search, Grep command has option -i

$ grep -i "Grep" cloud.txt
It print all lines in cloud.txt file as grep variations (Grep, grep) is presented in each line of file.

Count of words matched in a file

$ grep -c "Grep" cloud.txt
And output is 3, if we add option –I , output is 4.

Recursive search using grep command

By default Grep command search files in current directories, To do sub directories , have to use -r option

$ grep -r "Grep"  /usr/cloud

Please click +1 if you like this post.

Variable Arguments feature in java

Varargs Feature in java
Variable arguments feature is one of java language feature introduced in java 5. Java 5 introduced lot of new features like Enum feature[] etc.
method have multiple arguments, this arguments count are fixed, with Variable arguments feature in java5, method can have multiple arguments(zero to many) to be passed without defining number of arguments by specifying variable argument syntax. variable arguments are spcified in method defination by ellipse (...).

Before Varargs feature or prior to java 1.5:-
prior to java 1.5 version, developers has no chocie of variable arguments supplied but we

Java has a feature of method overloading in which same method can have different versions with changing arguments.

Advantages of Varargs feature:-

variable declarion not required at compile time or run time.
Clients have free control over passing variable arguments to Service API methods
backward compatability support for prior java versions

Variable argument syntax

We have to delcarate DataType ... arguments in method declaration

public void method(DataType ... arguments)

arguments are followed by ellipse ... meaning method accepts atleast zero arugments to mutiple arguments

Rules for Variable arguments

1. Varargs can be combined with other normal arguments.
2. Only one varargs in any method declaration
3. if there is combination of varargs and normal arguments, varargs declaration should be defined at last

JVM Execution for varargs:-

when variable argument is declared in method, java compiler of JVM loads that method and create a array of arguments of Data type

Varargs Simple example

package com.cloudhadoop.varargs;

public class VarargsExample {

static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
System.out.println(" " + sentence);

public static void main(String[] args) {
print("Hi", "How ", "are", "You");


and output is :- Hi How are you

Iteration of Varable arguments in java example

Variable arguments variable name is an reference to array of argument type. so we can use for each loop to iterate variable arguments

static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;

Why MessageFormat is introduced:-

I18n MessageFormat in javaBefore MessageFormat is introduced, we used to process the messages using String concatenation,
the disadvantages with String class processing is Strings are immutable objects, more objects are created in heap memory
and these messages order is not same for every language, because of this problems,
Sun has introduced text format classes like MessageFormat
String stringText="Hi"+ name+ "How are u";

MessageFormat is class in java.text package, introduced in java 5 language, and this text format class in java used to provide capabilities for Internalization.

java.util.MessageFormat class provides capabilities to display localization specific message and format the messages as per language specific.In Any application, messages are displayed to users when validation fails or request is submitted successfully.In real world programs, messages are stored in resource bundles or property files, prorgrams read the properties files based on language.

Basic example or usage of MessageFormat

Object userInformation={"John","success"};
String messageText=" user {username} data is submitted with {status} message";

MessageFormat messageFormatExample=new MessageFormat(messageText);

and output is user John data is submitted with success message

In above code, format() method formats strings by receiving {0},{1} arguments and MessageFormat is easy to learn and implement

How to format text message contains Date fields

MessageFormat also process which contains Date and currency fields, For this we have to specify the date format placeholders as below
Date currentDate = new Date();
System.out.println(MessageFormat.format("Current Date is {0,date yyyy-MM-dd}", date));

and output is Current Date is 2013-05-03

How to format text message contains number fields:-

Numbers in messages are formatted using {0,number,000.000} which display the numbers with 3 decimals

System.out.println(MessageFormat.format("Number is  {0,number,000.000}", 123456));

and output is Number is 123.456

How do we Internationalization in java

Usually applications are developed in english, but when we want our applications
to target users  or customers of different countries, Sun provides Internationalization concept in java.
Internalization or I18n is set of java classes or interfaces provided by java to support the global application in java. It means java applications works with multiple languages and multiple countries.

What are items to do in Internationalization
2.Time Zone
4. Message Format

when we target above things, application is named as internationalized applications

In simple terms, we develop applications in one langugae and can change to different local or localize the applications by doing the above things.

In java, java.util.Locale class holds localized information

For example, have coded for creating button in swing

JButton buttonEx=new JButton("Upload");

here, button label message is hard coded, It is very difficult if we want to develop this application to target different regions.

To Localize the application, we have to separate the labels and place them in property or resource file.

label message in resource file for US country is

button.upload.label =Upload–

In the same way we need to create one resource property file for each country or language. This can be added to application after application development is done.

button.upload.label = starten–

In java, Java.util.ResourceBundle is used to read resource bundles or property files.

In order to read resource files we can use java.util.ResourceBundle.

Creating resourceBundle

ResourceBundle rb = ResourceBundle.getBundle(basename, locale);

The above code will read the locale specific resource file , if it is not found, default locale resource is considered.

In Java applications, java.text.DateFormat,
java.text.NumberFormat, java.text.MessageFormat are used to achieve Internationalization

If you like this post, please share by clicking google +1 button

Running Junit tests with jmockit in eclipse

Junit is popular unit testing framework and jmockit is used to mock the objects.

eclipse is my favorite IDE (integrated development environment) software tool that provides writing,debug, deploy code and exusting test cases.

eclipse provides different plugins like junit and maven plugins

After installing junit and maven plugins to eclipse, we have to do following changes

junit and jmockit jars should be in project classpath
Add test directoroy in your project to eclipse project build path, eclipse compiles succesfully('Use as source folder').

Please see below screenshot for adding java build path in eclipse

Next step is to add the jmockit configuration to project jvm arguments
To execute the test class, do right click and select Run dialog (Run As --> Open Run Dialog)
and select Junit to execute tests
keep default settings in dialog and create a juni test for the class and click on arguments tab.
Add to vm arguments: '-javaagent:pathtothisjar/jmockit.jar' (if using Maven, use '-javaagent:${env_var:HOME}/.m2/repository/jmockit/jmockit/1.0/jmockit-1.0.jar')
Click 'Apply' or click 'Run'

Please share this post if you like this post.

What is Jenkins:-

Jenkins is open source tool developed for Continuous integration purpose

Sun has developed Hudson for building java projects, after oracle acquisition, Hudson is renamed as Jenkins (forked code base and enhanced by adding different plugins)

what is continuous integration:-

In software development, when we developed any code, developers compile the code using maven and run the test cases for the code, if failure happens, we will fix the code. For each code, we need to do manually.

but if multiple teams/developers are working on different modules of same web application,we need to do integration test by integrating all modules.

so we need a automated process to which each piece of code is tested for each new code changes, developer will fix the issues in case integration issues daily bases so that all your code is tested daily.

Jenkins server provides continuous integration platform and test driven development

Jenkins is open source which is plugin based development, you can extend jenkins server by adding differnt plugins

Jenkins is used to automate build and deployment process

jenkins is mainly integrated with two components

1. Version Control system like SVN,GIT
2. Build tools like apache maven.

Jenkins Continous integration server is developed in java, can be installed on tomcat or jetty application server. Jenkins can be extended by adding more plugins

Jenkins Continuous integration API features:-

1. Generate code colover reports and module build status
2. Integrated with different build systems like ant,gradle and maven
3. Integrate with different source code repositories like svn, cvs and Git
4. released/snapshot modules are pushed to different repositires like nexus
5. Deploy java projects to test, stage and Production environment
6. build status like success or failure are notified to developers

Advantages of jenkins:-

1. Build failures are cached at integration stage.
2. Automatic build report notification for each code commit changes
3. Jenkins is integrated with LDAP mail server to notify developers about build report failure or success
4. achieve Test Driven development and continuous integration agile development
5. maven release projects is automated with simple steps
6. Easy find out of bugs at early stage in development environment than production

Jenkins plugins:-

plugins are developed in java, can be added to jenkins to get more functionality. java plugins are easily install able

Please +1 if you like this post

REST API examples

REST is one of popular webservice in software world. REST is abbrvated as Representational State Transfer. REST API used to develop http based webservices

REST is similar to SOAP webservices, SOAP webservices can be accessed using object and methods, where as REST can be accesed using URL with http operations like GET,POST,DELETE,PUT.

REST API is used to write the API's for web applications to access the services.
REST API is protocal, can be developed and consumed in many languages like java, .net

REST API is simple to develop and simple to access the resources and each URI in REST webservice is accessing object methods in java world. each webservie is an asset to the organization

Usually there are different uses that deat with REST API's.
1. Producer :- users create a RESTfull service and host this services and expose this service to outside world with url This can be developed in any language
2. Consumer :- Consumer is actual user who access the REST webservice. users code in any language to consume the webservice by http communication

When we are developing any REST based API

Advantages of REST API:-

1. Can be easly deveop in any language on any platform
2. Easy to develop webservices
3 Easy to learn
4. Each web URI point to java method, so no other layers
5. Design and develop and consume is platform independent

Disadvantages of REST API

1. Not be usable for complex message distributed systems.
2. security mechanism has to be implemented on own, no standard protocal for security
3. Used only for HTTP based communication

Please click like if you like this post