Artikel Terbaru

Wednesday, 29 February 2012

Solution for java.lang.StackOverflowError exception in java

StackOverflowError is one of frequent exception/issue in java projects. This exceptions should not be caught by programmer but thrown by java virtual machine at runtime. whenever this exception is thrown, applciation stopped it's execution

java stackoverflowerror class overview:-

StackOverflowError extends java.lang.VirtualMachineError class which inturns extends java.lang.Error. so what is java.lang.Error?. Error class extends Throwable class specifies unusual errors that application unable to catch these exceptions.These exceptions are not programming related exceptions but thrown by java virtual machine.

StackOverflowError exception thrown in the method when the method are called recursively in infinite times.

Let us see the below program how it throws the exceptions

public class StackDemo {

 public static void main(String[] args) {
  StackDemo sd=new StackDemo();

 public void hello(){
output for the above program is exception with message like "Exception in thread "main" java.lang.StackOverflowError" thrown by applications.

The below is the program execution in memory in java vitural machine
1. Main method is starting point for the exectuion in the parent thread called main, once execution starts, main method makes one entry in the bottom of the call stack. please note that each thread has one own call stack.
2. After that,StackDemo Object is created and method hello() is called from the main thread, method area would be stored in the call stack above main () method area.
this method calls hello() method reursively calls same method infinte times, this makes call stack stores all method entires in memory. and size of the call stack is grown and the exception throwns when call stack unable to accomdates enough size for all these entries in memory. here stack is full with all the entries, StackOverflowError is thrown.
3.hello method is called recursively itself infinite times. so please make sure that avoid recursie infinite method calls.

This erros are thrown by java vitural machin, so be causeful with recursive calls in the methods.

Please leave a comment your thoughts on this.

Monday, 27 February 2012

How to inject enum object of java 5 in spring framework?

Inject Enum of java 5 in Spring Framework:-

Spring framework is popular opensource framework developing applicaitons in java.
Enum is java enumeration keyword introduced in java 5 features.

ususally, In Spring configuraiton file, we will inject different custom classes as well as predefined classes like Integer,String.

But injecting enum class in spring container is different as if we not correctly inject, we will end of with exceptions like "org.springframework.beans.TypeMismatchException: Failed to convert property value of type".
so what is the solution of avoiding TypeMismatchException in spring? The solution is to use either custom property editors in spring custom configuraiton files
we have to conver the enum to string to inject enum to class in spring.

This tutorials is to find out the ways to inject enum objects in spring.
here is the enum defination java class

package com.cloudhadoop.constants;
enum Day {
 private final int dayNumber;

 private Day(int dayNumber) {
  this.dayNumber = dayNumber;

 public int getDayNumber() {
  return dayNumber;


There are many ways to inject the enum object of java 5 in spring framework

one way is to inject the enum single value using enumProperty as described in the below screenshot
spring property editors are internally assigned the correct value to enum property

second approach is to inject using factory-method as in below screen shot.

The above approaches is light weight and spring container validates the configuraiton when container is stated

or other approach is to as is to assign all enum values using util:constant tag

This approach provides for bean validation in IDE's at development time. Please click below screenshot for the spring code configuration file.

The three apporaches works with enum in java with spring 2.5.6 version

Please share your comments on this topics

Wednesday, 15 February 2012

How to solve IllegalArgumentException in java with examples

Fix for IllegalArgumentException in java:-

IllegalArgumentException is one of frequent exceptions occured in java programming language. This exception extends RunTimeException class. These are also called UncheckedExceptions and need not to be handled in java code for this exceptions occurs at runtime. Exceptions in java are used to indicate that there is an error in your code.

IllegalArgumentException is good way of handling in the code.This exception occurs when caller calling method with incorrect arugment types for the methods. Methods in java are written in such way that we have to deal with valid data as well as invalid data,if it is valid data,process the data,and result is returned.In case of bad data, we have to throws this exception with detailed message to the caller. This is good way of handling invalid data with approriate message to the caller, then the caller should pass the correct data to the method.,

public class IllegalExceptionDemo {
   public static void main(String[] args) {
 MathServiceImpl service=new MathServiceImpl();
 System.out.println(" value "+service.divide(12,0));
class MathServiceImpl {
 public int divide(int number1,int number2)
    throw new  IllegalArgumentException("Number 2 can not be zero "+number2);
    return number1/number2;
The above code throws IllegalArgumentException when an argument is passed with zero values and the error message looks like as follows.
Exception in thread "main" java.lang.IllegalArgumentException: Number 2 can not be zero 0
 at MathServiceImpl.divide(
 at IllegalExceptionDemo.main(

Whenever any expceiton occurs, please see the complete stack trace for debugging, stack trace gives the exception type(IllegalArgumentException), detailed message(Number 2 can not be zero 0) and line number of the code( where exception is thrown.

method divide() is throwing exception when an agument(number2 is zero) using throw keyword
called method should have to handle the exception, throws this exception to the caller with proper message.Caller method need not be handled this exceptiona as this is runtime exception

In programming, IllegalArgumentExceptions are coded in the following scenarios to validated the invalid arguments for methods

1.Service API methods
4.Unit testing

When to throws IllegalArgumentException :-
This exception throwns for invalid arguments types for the below values

1.When object as argument in methods should check for null references before accessing the object methods
2.Invalid data check for methods arguments like checking for valid numbers, custom data check.

Please share your thoughts on how do you handle this exception.

Friday, 10 February 2012

Deque examples with tutorials in java

deque in java:-

Deque is abbrevateted as double ended queue like a normal queue, can store the collection of objects. It is one of the collections class introduced in java 6. Why deque is different from other collection classes? the answer is, in deque, we can inserts and deletes the objects from the both start, end of the the collection. where as normal collection inserts/deletes are happeneing at last only.

Deque is interface introduced in java 6 java.util.collections package which implements java.util package. Deque interface extends java.util.Queue which in turns extends java.util.Collection, so we can insert/delete/iterate of all the objects that collections provides.

Deque is interface so you can not create a objects,Deque is implemented by two classes ArrayDequeand LinkedList.

ArrayQueue is just like array list implementaiton of queue, LinkedList is implementation of double linked list.

So you got the basic idea on ArrayQueue, When i am learning Deque, ArrayList class came into my mind, and immediately question came into my mind, what is the difference between ArrayQueue and ArrayList?.When to use ArrayList and ArrayQueue?. Answers for these questions are found in my below table.

ArrayList ArrayDeque
Elemetns are inserted/deleted at any location including last Elements are inserted/deleted at both ends i.e start and last
Elements are accessed by index elements are accessed by starting index or ending index
ArrayList are growable array of objects ArrayDeque are growable array of objects,better for implementing statck(LIFO) or Queue(FIFO)
Performances better for accessing elements, not for insert/delete operations Queue performs better for insert/delete operations compared to access elements

Basic Deque examples :-

1.How to add elements to Queue?

For queue, we can add object to deque in may ways one way is using add version methods other is offer version methods as well as push() method
Deque dequelist=new ArrayDeque();

System.out.println(" "+dequelist);

and output is
equity Derivative commondities stocks
add() method ads the elements at starting list of objects
addFirst() method adds the elements starting list of objects
addLast() method adds the lements end of the list.

offer() version of methods also do the same as like add() version of methods.
but the difference is if the deque is fixed size of collection, we can use Offer version of methods.
if we add objects using Add methods for fixed queue, it throws IllegalStateException if objects are unable to add the objects

There is one more method i.e push() which adds an element to the end of queue,returns true if added, otherwise returns false, throws IllegalStateException if no enough space in the collection

2.How to remove elements in Deque?:-
Deque API provides many types of methods to delete the objects from the queue 1. remove version methods 2. Poll Version methods 3. using pop() method
deque provides the following methods to remove elements.
poll() method deletes the first matched object from the deque
pollFirst() method deletes the first object from the deque
pollLast() method deletes the last object from the deque

remove version of methods also do the same thing like poll() methods except it throws NoSuchElementException if collection is empty.
poll() methods returns null if the deque is empty

there is one more method i.e pop() which deletes an element from the queue,returns delted element.

3.How to Access elements in Queue?:-
traversing elements in deque is same as list, we can use either Iterator, for each loop, or using specific methods using peek()

Iterate objects in Queue:-
//using iterator for deque
Iterator forwardIterator=dequelist.Iterator(); // for forward iteration
Iterator BackwardsIterator=dequelist.descendingIterator(); // for iteration of elements in reverse order
System.out.println(" "+(String)forwardIterator.nextElement());
//using for each loop in deque
for(String element:dequelist){
and output is
equity Derivative commondities stocks

get the specific elements in deque:-
the above methods retrieves the elements from the queue, elemetns throws NoSuchElementException if queue is empty, where as peek returns empty

4.How to find if element exists in deque?:-

To check an element available in queue, we have to use contains(Object) method, returns true if available,else return false

Please share your comments if you like this posts.

Java NumberFormat tutorials: 3 Examples of NumberFormat in java

Basic Usage of NumberFormat in java


When we are developing any applications targeted to different countries, the presentation of the data shoulld be

specific to each country eventhough data storage is always same. This is tedious task for java programmers to handle of formating the same data to specific country. java introduced Globallization and localization concept. As part this there are number of formatting classes including NumberFormat are introduced in java.text package.

What is internalization(i18n) and localization in java?
internilization is a concept programming technique to code in sucha way that any software applicaitons works for multiple languages as well as countries. data from application should be displayed as per the locale specific.

Usually, considering financial applicaiton, the data stored in backend database is always same ,but the format for displaying is always different for each country. that means USA has dollar symbol as currency in representing any price of object and dollar always displayed before the price number ($100) Where as India has different symbol for currency and this symblo should be displayed after price of any number (100 Rs). So we have to write a applicaiton in sucha way that it supports multiple languages and multiple countries.

one more scenario is if we develope a web applicaiton that is targeted to different countries to display such data, we have to handle the different scenario as per below
the 1000000.11 number is stored in database and should have to display based on thousand separator as per specific country, that means, If i am accessing the applicaiton from USA, USA specific format should be displayed.

1,000,000.11 should be displayed for USA people
1 000 000,11 should be displayed for Genrmap people
The number stored is independent of any local, but the display should as per the locale

NumberFormat solves all above display of all the number formating capabilities as just mentioned above.

NumberFormat provides custom Format to format the numbers based on applicaiton needs

java provides API for solve all those display formats NumerFormat is one of the class in java.text, with these we can format the below cases.

1. Format the number as per the country and language
2. Format the numbers as per the currencies
3. Format the number percentages like thousand separator and precision

NumberFormat is abstract factory class which we can create objects using static getInstance() method Only

NumberFormat examples:- These examples are used to give basic idea of NumberFormat class or Subclass using custom format.

1. How to format a number to thousand separator?

We can do in many ways to format the format the number into thousand separator. One way is to use String.format() method 2. Using regular expression
and third way is using NumberFormat java class.

pasting the code using NumberFormat example.

Locale usaLocale = new Locale("en", "US");
Locale canadalocale = new Locale("fr", "CA");
NumberFormat formatusa = DecimalFormat.getInstance(usaLocale);
System.out.println("USA " + formatusa.format(123456789));
NumberFormat formatCanada = DecimalFormat.getInstance(canadalocale);
System.out.println("Canada " + formatCanada.format(123456789));

value is 123456789 and out put value should be separated with thousand separator and returned output 123,456,789

2. How to format the number to decimal places. or DecimalFormat example

DecimalFormat class is used to format the number to decimal places.NumberFormat is parent class for DecimalFormat. Mosttly decimal Format class is used to format the number specific to local settings

DecimalFormat df=new DecimalFormat("##.0000");
System.out.println("Decimal value with 4 digits "+df.format(12345.893477));

There are two things to note as we are providing pattern "##.0000" to DecimalFormat object
Format object format thes double/float number to 4 digits after decimal point.
This example also round the double value apply the decimal places for specific pattern.

3. How to display the number in currency format?

Locale englishLocale = Locale.US;
String numberDisplay = NumberFormat.getCurrencyInstance(englishLocale).format(89756.862);
Locale germanyLocale = Locale.GERMANY;
String numberDisplayInGermany = NumberFormat.getCurrencyInstance(germanyLocale).format(89756.862);
System.out.print(" "+numberDisplay+" "+numberDisplayInGermany);

and the output should be
$89,756.86 89.756,86 €

Hope you understood the basic usage of NumberFormat class in java . Please share your comments on this

Monday, 6 February 2012

Best examples of using ArrayList Class in java: java array list samples

Array List in java:-

ArrayList is implementation of List interface in java.utils package.ArrayList stores the collection of objects in the order of insertion. ArrayList stores the objects and grows the size of the list dynamically that's why array list is re sizable array. where as array is static once assigned the values, the size is fixed.In the real time programming, ArrayList is used to manipulate the collection of custom objects.

Arraylist is popular collection framework used in every day life of java developer.
In most of the backend programming, HashMap is used to store as temparary cache for either request scope or session scope.HashMap is combination of key and values. key and values should be either String,primitives or any custom object. The key stored in the HashMap is based on the hashCode computed for key'object Map is implemented by HashMap in utils package

Important points to remember for ArrayList:-
1.Object stored in ArrayList are insertion order
2.ArrayList is used to store the collection of objects with size increasing dynamically
3.ArrayList stores the objects including null values.
4.ArrayList is not synchronized

1. How to create a ArrayList:-
ArrayList has default constructor as well as constructor with integer parameter.
arraylist can be intialized with integer number also.

ArrayList emptylist=new ArrayList(); or
 ArrayList list=new ArrayList(10);
The above lines of code create ArrayList object with empty size as well as fixed size of array list.second case, the fixed size is 10

2. How to add Objects to ArrayList.
ArrayList provides add method to add the object to ArrayList
he map.
ArrayList list=new ArrayList();

3. How to show the elements in the ArrayList:-
using for each look, we can iterate each object in the list

for (Object str : list) {
 System.out.print(" " + (String) str);
and the output is
One Two Three Four Five
. Always make sure that you check for null check for list as it will throws NullPointerException if list is null. add the following code snippet for avoiding NullPointerException in ArrayList
add the for loop code here

4.How to find the size of ArrayList?:-

Java arraylist API provides size() method to find the number of elements in the HashMap
return the size of the arry list , as 5 is returned for the above code

5.How to check if the object/element is find in ArrayList:-
arraylist api provides contains() method which returns true if particular object found in the systme
System.out.print(" " + list.contains("One"));
and also other way is to use indexOf() method to get the index of an element in arraylist. This method returns position if the element is found the in
array list else return -1 if element/object is not avialble in array list.

6. How to Convert ArrayList to array:-
As array list to array is one of common mechanism in day to day programming.

collection API provides arrayList.toArray() method used to convert to array of objects
String[] strArray=(String [])list.toArray(new String[list.size()]);
  for (Object str : strArray) {
   System.out.print(" " + (String) str);
and the output is
One Two Three Four Five

7.How to convert array to ArrayList in java:-
to conver the array to arraylist, collection API provides java.util.Arrays class asList() method to be passed to ArrayList constructor
String[] strObjects = {"One1", "two2", "three3", "four4"};
List arrayList= new ArrayList(Arrays.asList(strObjects));

8.How to remove/delete element in list:-
ArrayList has remove method to remove the object from the list.

9.How to get the elements in list:-

list provides get() method to return the return the object found in the list

if element is not found, null is returned.

10.How to sort objects in ArrayList:-

if we are displaying the objects from the list, ther order is of insertion order onlly.
to sort the objects in the arraylist, collection api provides Collections.sort(List) method to sort in natural order.
This elements sort in natural order by the hashcode as well equals method default implementation order.

if we wan to display the custom order for primitive types or object based on member variables, we have to write our custom comparable java class which is passed to Collections.sort() method as other parameter.

Collections.sort(list,Comparable interface);

I hope you got the basic idea on array list with examples to work.

Please share your comments on this.

java enums tutorial: Best 10 examples of enum in java

Enums in java:-

Enum is one of the cool language featured introduced as part of java 5 version.
enum values are constants meaning which can not be changed. These constants are specified using upper case letters as per java coding specifications

Enum is introduced in java 5 version,Before java 5 was introduced, we have to write our own constants to handle enum functionality as follows
public class MonthsConstants{
public static final String JAN="1";
public static final String FEB="2";
public class MonthsConstantsTest
{ int monthsCode; //can assign any value like 1,2 or 100

You have to handle all your constants yourself and causes error prone.
These values are valid type for compile time only and gives error if wrong type is assigned to these values. Moreover you can assign any values
if we want to add new constants, it would be more work is required for maintenance of your code.Because of all these enum class is introduced.

By default, enum implements java.lang.Enum which implements and java.lang.Comparable interfaces.

java enum API provides different methods like toString(),name() as well as valueOf() methods

I am listing down the best enum examples in java
1.How to define enum class?
This is one of the way to define enum in java
public enum Months{
This is going to create in java class and enum class name. Please note that enum constants has semicolon at the end of constant defination.

2.How to define enum inside an other class:-
public class MonthsClass{
public enum Months{
Months monthsNames;
In the above example, enum class is created in inside the class, please note that semicolo is not required after defining enum constants.

3.How to create enum object?:-
MonthsClass monthsObject=new MonthsClass();
we can create enum objects using new operator. and also we can attach constants to the enum class
4. how to define enum constructor :-
public enum Months{
private int monthCode
Months(int monthCode){
public int value(){
return monthCode;
enum constructor in enum are private, meaning outside classes should not able create enum objects creation.

5. How to compare Enum objects in java:-
normally we can compare objects using == and equals methods
enum constants can also be compared using the same.
if(Months.JAN==Months.FEB){return true else return false;}
we can also use equals method to compare the enum objects of same type.

6.iterate enum constants:-
enum class provides values() method for iteration which returns list of enum constants in the order of constants creation.

for(Months months:Months.values()){
System.out.print(" "+months);
and output is:-
7.How to convert enum to integer ?:-
We have encountered in our programming to convert enum constant to integer.
As defined enum declartion in steps #4
Months months=Months.Jan;
Integer int=new Integer(months.value());
value method in enum provides the value for the enum constants.

8.How to convert integer to enum constant?:-
we have to define the following method in enum class for returning the Enum for the given input as integer
static Months getMonths( int monthCode ) throws Exception
for (Months months : Months.values())
if (months.value() == monthCode)
return months;
Hope this solves the conversion to enum by providing integer as input to the above method

9. How to convert String to enum object?
enum class provides valueOf(String )method to pass the string as an argument, which return enum constants
Months month=Months.valueOf("JAN");
Months month=Months.valueOf("abc");
For first line in the above code,month object prints the string value as jan

second, valid string is not passed to enum class, it throws java.lang.IllegalArgumentException with message No enum constants for your class. to use enum class in switch condition:-

one of the coolest feature of enum is we can use enum objects in switch case as like a primitive type
Months month=Months.JAN;
 case JAN:
 case FEB:

Advantages of Enum class:-

1.By default enum classes are implementing serialization, and overidng equals and hashcode methods so no need for explicit serialization implementation
2.With usage of Enum class, EnumSet and EnumMap are introduced,collection of enums operations can be achieved
3. Maintenance of code using enums is very easy

Disadvantages of Enum class:-
enum class is extending java.lang.Enum, the classes in java.lang are final,so enum classes can not be subclassed.

Hope you understand enum examples in java.

Please share your comments that how you are using the enum class in your development/

3 ways to debug maven build : maven debug tutorials

Maven build debug

Maven is automated build project management tool and automates the build process by defining the all the dependencies in pom.xml.Developers encounters lot of issues while building maven project in development phase as well as release phase.we need to know the ways to debug any issues with maven build.I am listing down the different ways to debug the maven build issues.

There are number of ways to debug an maven project.
I am listing down the required steps for findout the real issues.

1. maven debug mode:-
if you are experience with running maven goals like compile or install, mostly informative message will bedisplayed. if any failure happens, These messages are not helpful to find out the exact cause.
In such case, try to run maven with -X flag to give the clear message of where the error is occured and also plugin configuration and detailed class loading information which is very helpful for the coders to find the real cause of an issue. This is perfect suitable debug option for maven plugin coders.
mvn -X  prints debugging messages
 mvn -e shows error messages
Please remember that this is debugging information for what maven do while building your project. This is not for your project debugging. i.e different concept. i will write one more post about the java project debug tips later posts.

This option will start the maven in debug mode. It will give the complete information messages like what are the different dependencies that are loading to your project and what goals are running.

2.dependencies issues in maven:-

In a real time, for maven project build,we have seen that our project has direct dependencies as well as indirect dependencies.

suppose in your project, you have direct dependency on one module say log4j-1.2.12 and you have other indirect dependency of log4j-1.2.12(coming from spring 2.0.6 which has dependency for your project). This would be the case of your project having two same modules(log4j) with different versions. This would be an class incompatible issue once your project is started in webserver. Then you have to keep the required module in your pom.xml and ignoring other module by specifying exclusion configuration.

To find out the dependency tree for your project, you have to use the below command
mvn dependency:tree
This list out all the dependencies for your project in tree explorer format.all these dependencies are downloaded to your local repository.

3.Debugging tests with maven surefire:-

we will use mvn test for running test cases of your maven project. As you know maven surefire plugin is used to run with your unit test of your project.

you have to provide the maven.surefire.debug property with maven test goal
mvn -Dmaven.surefire.debug test

This will run the tests in separate process.This will listen on port 5005. You can attach this process to eclipse for remote debug.
In the eclipse you have to create and configure the maven debug options as follows.
hostname is localhost
and port  is 5005

This is one of coolest feature provided by maven with eclipse remote debugging.
whenever we started the maven test case execution, you can put break points for stopping the debugger in your test classes for debugging purpose. Once the maven execution is over, eclipse debugger terminate the process.

and other way is to not to run the debugger in fork mode meaning is to execute the tests in the same process, we can use

mvn -DforkMode never test

Top 10 examples of find command in unix and linux

Best Find command examples in linux and unix:-

find command is one of frequent command used in linux and unix operating systems.
find command is used by unix/linux users to search the specific files in directory as well as sub directories.
 find command examples in unix and linux
I use this command as part of my programming development with java for searching logs as well as java files in linux operating system.

In windows enviornment, users have the ability to search the any files directly using windows explore. But in Linux/Unix, we have to use command based options to search files.

Most of the people working on development projects, need to know the basics of find command, because they need to search source code files as well as applicaiton logs where the errors occured.

Find command can be combined with grep and other file related commans to make the powerful search in linux/unix.

So i am listing down the some of the find commands that i use daily as part of my software project development.

Find command options in unix and linux:-
usuall find command syntax is as follows.
find {directorytosearch} {options}

The following are the options to be given to find command.
1.File name to be search in the list of files.
2. directory or list of files to be specified where search for file name is to find.
3. type of files or directories to list all the files in the directory and subdirectories?:-

find . or find . -print
. represents the all the files in the current directory as well as sub directory.
this command shows all the files in the directory and sub directories to the console.

2. how to find files using name in the current directory:-
find . -name "" 
the above command, file name "" specified using the option -name searched in the current directory specified by option .
and print the file name to console.

3.How to execute last executed find command:-
find . -name
The last executed command usually stored in the session level cache, so typing the same command is time consuming alternative step is using this command will execute the last executed find command.
This ! can be used with any linux command to executed the last specified command.

4. Find all files that are owned by specific user?
$find /directory -user kiran 
usually if we search the files that are not owned by specific user, it gives output as 'filename and permission denied' message to the user

5 how to find file search using name ignoring case sensitive :-
$ find . -iname
Here the file name case is ignored and displays all the files with ignoring case

6. Find the files which are modified in the last one day:-
$ find . -mtime 0
This is very useful for applicaiton log changes that were modified in the last 24 hours. This is my one of the favourite find command bash to know the modified files in the last one day.

7. How to find the files which are modified in the last 10 mins in unix.
find . -mmin 10
This is basicall used to search files which are modified/created in the last 10 mins. This is one of my favourite find command
and few more examples for finding the modified files between 10 and 20 minutes in the linux
find . -mmin +9 -mmin -21 

8.How to list only the subdirectories and directories in file system.
find . -type d
9.How to find file names in subdirectory that is one level down current directory?
find -maxdepth 2 -name ""
-maxdepth 2 means subdirectories i.e level 2
if we want to find the files in the current directory , we have to use -maxdepth 1 with find command.

10.find all files based on file types?
normally, with find command, we search files only. with find command by providing -type option, we can search directories and symlinks in linux
1.Find regular files in linux
find . -type f
1.Find directories in linux
find . -type d
Find all the symlinks using find command
find . -type s

I hope you understand the basics of find command with examples.
I will write one article about advanced usage of find command in linux and unix.

Please share your comments .

Sunday, 5 February 2012

Top 10 Examples of HashMap in java : HashMap tutorial

How HashMap works in java:-

HashMap is implementation of Map interface in java. HashMap is popular collection framework used in every day life of java developer.
In most of the backend programming, HashMap is used to store as temparary cache for either request scope or session scope.HashMap is combination of key and values. key and values should be either String,primitives or any custom object. The key stored in the HashMap is based on the hashCode computed for key'object Map is implemented by HashMap in utils package

Important points to remember for HashMap:-
1. Order of keys stored in HashMap is based on hashing. Eventhough order is not fixed.
2.HashMap allows null keys and null values
3.HashMap is not synchronized meanning is not thread safety
4. Hashmap is fail fast meaning, if we are modifying/adding/remove any object while iteration of HashMap, it throws ConcurrentModificationException

keys stored in order of calculating the Hashing mechansizm .

1. Create HashMap Object using new in java:-
HashMap provides default constructor as well as other constructor with integer number
HasMap map=new HashMap() or
HasMap map=new HashMap(10)
The above one of the two lines create HashMap with emptry constructor or construtctor with integer. This number represetns initial capacity

2. Adding Objects to HashMap.
HashMap provides put method to store the key and values in the map.
HashMap map=new HashMap(10);
map.put("11", "oneone");
map.put("21", "twoone");
map.put("31", "threeone");
map.put("41", "fourone");

3. Itertion of all values in HashMap:-
HashMap provides values() method to iterate all the values
Collection collection=map.values();
 for(String str:collection){
  System.out.print(" "+str);
values() return the colleciton object which we can used in for each loop to return the each object
out put is
twoone fourone threeone oneone

4.Find out the size of hashmap:-

size() method is used to find out the size of the hashmap
return the size as 4 for the above map.

5. Check if key object available in HashMap:-

To check if specific key exist in HashMap, we have to use containsKey(Object obj) of HashMap. if the key is found in the map, it returns true other wise it returns false

map.containsKey("11") return true
map.containsKey("134") return false
6. Check if value object available in HashMap:-

To check if specific value exist in HashMap, we have to use containsValue(Object obj) of HashMap. if the value is found in the map, it returns true other wise it returns false

map.containsValue("oneone") return true
map.containsValue("cloudmap") return false
7. How to delete object from HashMap:-
map provides remove method which will removes key and value from the HashMap object.

To delete key object from HashMap, we have to use remove(Object key) method of HashMap and returns the value for that key

remember only key object should be passed to remove method and returns value for that key if removed, otherwise returns null.

String value=map.remove("21");
the above key "21" is found in map,then removes that key and value pair from the map, and returns the value object.

if key is not found, then null is returned.

8. remove all the objects from the HashMap:-

to remove all the key and value pairs from the map, use clear() method of HashMap.

After clear() method is used, if isEmpty() is called , it returns tru as all the objects has been removed.

9. Converting Map keys to Set:-

To convert the HashMap keys to set, we have to use keySet which returns Set of keys
Set keys=map.keySet();
 for(String str:keys){
  System.out.print(" "+str);
10. How to Synchrnoze HashMap in java:-

HashMap is not synchronized. meaning more than one thread modifies the state of an object. But we can mak HashMap as synchronized if

Map synchronizedHashMap = Collections.synchronizeMap(map);

Friday, 3 February 2012

Maven Clirr plugin example : maven2 plugins

maven clirr plugin  from org.codehaus.mojo:-
Maven Clirr  plugin is used to give the report of your current project by comparing with other same old project.Basically if we configured this plugin to your project, it checks your project jar with an older version jar that is configured in pom.xml to compare.This plugin is to compare the source code as well as jar comparisions for incompatable issues to find in early stage of any module before releasing the module.

Why maven clirr is important before maven release:- 
 if you are releasing any maven module, that module should be well worked with backward combatble with modules that uses it. Once module is released. that module is used by different developers of different teams, if you find any issues after release, then we have to fix that issue rerelasing is the tedious task. To avoid this, It is always good idea  to use clirr plugin execution checks against previous version to verify compatability before releasing any your project module. This will specify any binarly combatable issues with the previous code.
Adding this plugin is stright forward in pom.xml. we have to add this plugin element in pluginManagement section of your project's pom.xml. This is same process for any new plugin to add to your project.

org.codehaus.mojo is providing the plugin to maven repository. Once this plugin is configured,clirr-maven-plugin is downloaed into your local repository.

Maven Clirr plugin reporting:- Once you configured the clirr plugin, you have to generate the reports for the combatable issues.
This reports shows the list of all errors and warnings with detailed messages messages
if your current project version is 1.2, you need to check with oldest project jar (1.1), then you have to define that version in comparisonVersion element in the reporting section.

How to generate the Clirr report?
Once plugin configuration and reporting configuraiton is configured in pom.xml, we have to run maven site command to generate the report.
maven site
By running this on command prompt, This will generate a clirr html report under the target/site directory with clirr-report.html
Alternatively you can also run mvn clirr:clirr to generate the report .
mvn clirr:clirr

Hope you understand the basics of maven clirr plugin with examples.

Please feel to share your comments on this.