Category Archives: Java Concepts

Static Blocks in Java with Example

Static block in a class are the block of code portion which  executed only once,

1.Before creation of any object of the class.

2.Before any static member of the class in been accessed.

Example: Before creation of any object of the class

package com.devil.java.concept;

public class StaticBlockForConstructor {

static {
System.out.println("I am in first static block");
}

public StaticBlockForConstructor() {
System.out.println("I am in the constructor");
}

public static void main(String args[]) {
StaticBlockForConstructor constr1 = new StaticBlockForConstructor();
StaticBlockForConstructor constr2 = new StaticBlockForConstructor();
}
}

 
Important point to note that static block is been exceuted only once when we create first object constr1
and not when second object constr2 is been created .Output of the above programme is :

I am in first static block
I am in the constructor
I am in the constructor

We can use multiple static blocks as well, they will be executed in the order they are defined in the class, like:

package com.devil.java.concept;

public class StaticBlockForConstructor {

static {
System.out.println("I am in First static block");
}

static {
System.out.println("I am in Second static block");
}

static {
System.out.println("I am in Third static block");
}

public StaticBlockForConstructor() {
System.out.println("I am in the constructor");
}

public static void main(String args[]) {
StaticBlockForConstructor constr1 = new StaticBlockForConstructor();
StaticBlockForConstructor constr2 = new StaticBlockForConstructor();
}
}

Output of the above programme will be :

I am in First static block
I am in Second static block
I am in Third static block
I am in the constructor
I am in the constructor

Example: Before any static member of the class in been accessed.

package com.devil.java.concept;

public class StaticBlock {
static int i;

static {
i = 10;
System.out.println("static block called here");
}

public static void main(String args[]) {

System.out.println(StaticBlock.i);
}
}

Output of the above programme will be:

static block called here
80

If we use multiple variables , in that case also static block will be executed only once like:

package com.devil.java.concept;

public class StaticBlock {
static int i;
static int j;
static int k;

static {
i = 80;
j = 90;
k = 150;
System.out.println("static block called here");
}

public static void main(String args[]) {

System.out.println(StaticBlock.i);
System.out.println(StaticBlock.j);
System.out.println(StaticBlock.k);
}
}

Output of the above programme will be:

static block called here
80
90
150

So that is it about the static block in Java. Hope it will be helpful.

Generics in Java with examples

Generics has been introduced in java 1.5.Generics provide many advantage like code re-usability and detect compile time error related to type safety.

Idea is to pass object as an parameter to the class, function and interface(like passing object Integer,Double or any other user defined object).
Primitive types like int, double etc are not allowed to pass as an parameter.

Generic Class Illustration:

package com.devil.java.generics;

public class GenericClass<T> {
T genericObject;

public GenericClass(T obj) {
this.genericObject = obj;
}

public T getGenericObject() {
return genericObject;
}

}

For creating object for the above class:

When String is passed as an parameter:

GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");

When Integer is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

When Double is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(80.89);

Now if we try to pass primitive type as an parameter,it will give compile error.Like below code will give compile error.

GenericClass<int> doubleObject = new GenericClass<int>(80);

Example illustrating above object (not primitive type)passing is:

package com.devil.java.generics;

public class GenericClassMain {

public static void main(String args[]) {
GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");
String str = stringObject.getGenericObject();
System.out.println("String name from Generic is: " + str);

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

Integer intNumber = intObject.getGenericObject();
System.out.println("IntNumber from generic is :" + intNumber);

GenericClass<Double> doubleObject = new GenericClass<Double>(80.89);

Double doubleNumber = doubleObject.getGenericObject();
System.out.println("Double Number from generic is :" + doubleNumber);
}
}

Output of the above Programme will be:
String name from Generic is: Merry Christmas
IntNumber from generic is :10
Double Number from generic is :80.89

We can pass multiple type parameters as well like:

class name<T1, T2, …, Tn> { /* … */ }

Like in this example , we are passing three parameter.

package com.devil.java.generics;

public class GenericClassMultipleParameter<T, S, U> {
public T obj1;
public S obj2;
public U obj3;

public GenericClassMultipleParameter(T ob1, S ob2, U ob3) {
this.obj1 = ob1;
this.obj2 = ob2;
this.obj3 = ob3;
}

public void printParameter() {
System.out.println("First Parameter is: " + obj1);
System.out.println("Second Parameter is: " + obj2);
System.out.println("Third Parameter is: " + obj3);

}
}

Programme to use above class is :

package com.devil.java.generics;

public class GenericClassMultipleParameterMain {
public static void main(String args[]) {
GenericClassMultipleParameter<String, Integer, Double> genericObject =
new GenericClassMultipleParameter<String, Integer, Double>(
"Merry Christmas", 100, 900.67);
genericObject.printParameter();
}
}

Output of the above programme will be:

First Parameter is: Merry Christmas
Second Parameter is: 100
Third Parameter is: 900.67

Generic Function Illustration:

In the generic function we will use parameters between access modifier and return type like this:

For one parameter:

public <T> void printDetail(T object){/*....*/ }

For multiple parameters:

public <T,U,V> void printDetail(T object1,U object2,V object3){/*....*/}

Example illustrating using of one parameter:


package com.devil.java.generics;

public class GenericFuncton {

public <T> void printDetail(T object) {
System.out.println("Passed object is :" + object.getClass().getName()
+ " and value is :" + object);
}

public <T> T getObjectDetail(T object) {
return object;
}

public static void main(String args[]) {
GenericFuncton function = new GenericFuncton();
function.printDetail("Merry Christmas");
function.printDetail(800);
function.printDetail(456.90);

String str = function.getObjectDetail("Merry Christmas-2016");
System.out.println("Value of returned String object is: " + str);
/**similarly we can get do for other parameter */

}
}

Output of the above programme will be :

Passed object is :java.lang.String and value is :Merry Christmas
Passed object is :java.lang.Integer and value is :800
Passed object is :java.lang.Double and value is :456.9
Value of returned String object is: Merry Christmas-2016

Example illustrating using of multiple parameters:

package com.devil.java.generics;

package com.devil.java.generics;

public class GenericFunctonMultipleParameter {
public <T, U, V> void printDetail(T object1, T object2, T object3) {
System.out.println("First Passed object is :"
+ object1.getClass().getName() + " and value is :" + object1);

System.out.println("Second Passed object is :"
+ object2.getClass().getName() + " and value is :" + object2);

System.out.println("Third Passed object is :"
+ object1.getClass().getName() + " and value is :" + object3);
}

public static void main(String args[]) {
GenericFunctonMultipleParameter function =
new GenericFunctonMultipleParameter();
function.printDetail("Merry Christmas",800,456.90);

}
}

Output of the above programme will be :

First Passed object is :java.lang.String and value is :Merry Christmas
Second Passed object is :java.lang.Integer and value is :800
Third Passed object is :java.lang.String and value is :456.9

Advantage of using Java Generics:

1.Code re-usabilty:We can write a generic method/class/interface once and use for any type we want.

2.Using of generics will detect errors at compile rather than throwing error/exception at run time.like if we do not use generic collection (say ArrayList) in our example.It will allow insertion of 10 (Integer type) at compile time but will throw exception at run time.

package com.devil.java.generics;

import java.util.ArrayList;

public class NoTypeSafety {
public static void main(String[] args)
{
ArrayList al = new ArrayList();

al.add("Banglore");
al.add("Kolkata");
al.add(10); // Compiler allows this

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);

// throws Runtime Exception
String s3 = (String)al.get(2);
}
}

Output will be :

Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.devil.java.generics.NoTypeSafety.main(NoTypeSafety.java:18)

Using of generics will solve this problem and will detect error at compile time, like this:

package com.devil.java.generics;

import java.util.ArrayList;

public class TypeSafety {
public static void main(String[] args)
{
ArrayList <String> al = new ArrayList<String> ();

al.add("Banglore");
al.add("Kolkata");

//  Compiler doesn't allow this
al.add(10);

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}

Compiler error will be :
The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

 

 

So this is all about using of generics  in Java.Let me now if there is any questions.

Working and Difference of HashMap ,HashTable,SynchronizedMap, ConcurrentHashMap,TreeMap,SynchronizedSortedMap and ConcurrentSkipListMap

All the above five class implementation are of Map interface.Map object store an key,value pair in the memory.Both key and value should be object not some primitive type like int,float.

Lets start with HashMap and HashTable.Hashtable is synchronized but HashMap is not synchronized other difference is that  in HashMap we can put null as an key or as an value but in HashTable  we can not put null as an key or as an value.

The Below Code example show that in HashMap we can put null as an key or as an value but in HashTable  we can not put null as an key or as an value. Although there is no problem at compile time but it(HashTable) will throw exception at run time.

 

package com.devil;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class MapExample1 {

public static void main(String args[]) {
Map<String, String>hashMap = new HashMap<String, String>();
hashMap.put(null, null);
for (String str : hashMap.keySet()) {
String value = hashMap.get(str);
System.out.println("HashMap Value:-" + value);
}

Map<String, String>hashTable = new Hashtable<String, String>();
hashTable.put(null, null);
for (String str : hashTable.keySet()) {
String value = hashTable.get(str);
System.out.println("HashTable Value:-" + value);
}

}

}

 

Output will be—

HashMap Value:-null

Exception in thread “main” java.lang.NullPointerException

      at java.util.Hashtable.put(Unknown Source)

      at MapExample1.main(MapExample1.java:17)

If we are inserting  multiple keys as an null in HashMap.Than latest insertion will be considered as an entry in to the HashMap

package com.devil;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class MapExample2 {

public static void main(String args[]) {
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(null, null);
hashMap.put(null,"HashValue");
for (String str : hashMap.keySet()) {
String value = hashMap.get(str);
System.out.println("HashMap Value:-" + value);
}

Map<String, String>hashTable = new Hashtable<String, String>();
hashTable.put(null, null);
for (String str : hashTable.keySet()) {
String value = hashTable.get(str);
System.out.println("HashTable Value:-" + value);
}

}

}

Output will be—

HashMap Value:-HashValue

Exception in thread “main” java.lang.NullPointerException

      at java.util.Hashtable.put(Unknown Source)

      at MapExample2.main(MapExample2.java:17)


Hashtable is synchronized i.e methods for getting and putting element are made tothread safe by putting ‘synchronized’ keyword before the methods.

In HashMap get() and put() are:

public Value get(Object key) {

Value v;

—implementataion—

return v;

}

public Value put(Key key, Value value){

Value v;

—implementataion—

return v;

}

And in Hashtable get() and put() are: 

public synchronized  Value get(Object key){

Value v;

—implementataion—

return v;

}

Public synchronized Value put(Key key, Value value) {

Value v;

—implementataion—

return v;

}

 

Synchronization and Concurrency: 

Concurrency means number of executing units(like thread)are doing their work on the shared code portion(Class,Method)simultaneously without outputting wrong result. And Synchronization is the way to achieve Concurrency. Proper usage of synchronisation make sure data integrity and sanity in a multithreaded environment (which is concurrent environment). Use of ‘synchronised’ keyword and use of locks are some of the synchronization technique used in Java.

Now Collections.synchronizedMap: 

Collections.synchronizedMap(Map<K,V> m)is wrapper class for HashMap and is almost same as that of HashTable. It has‘synchronized’ keyword internally on every method. Functionally, HashTable and  SynchronizedMap are same.Both are slow,thread safe and had lot of performance overhead due to synchronization mechanism.Now in between HashMap and HashTable,HashMap should be used always for single thread environment .If in case we need to use it in multi- threaded environment, we should use Collections.synchronizedMap(Map<k,v>m) which gives synchronized HashMap.

 Also HashTable is from JDK1.0 and rest of the collection framework(Map,Set,List)is from JDK 1.2 and HashTable is kind of obsolete data structure now. Its retained in further JDK version just to support legacy code.

Now in multithreaded environment when size of HashMap becomes large,Using of Collections. synchronizedMap (Map <K,V> m) or Hashtable make our code very slow since in both the cases lock is acquired on whole object.

So now in this situation ConcurrentHashMap comes in rescue which was accommodated in JDK1.5 and is part of concurrent package(java.util.concurrent). ConcurrentHashMap use segmentationInternally, by using segmentation it lock only some portion of the map object and rest of the portion can be processed by different thread on different segments of the Map (We can see source code for ConcurrentHashMap on how segmentation works internally).

So below is the whole summary:

HashMap:Use it in single threaded environment. When only one thread is accessing our Map object.Here null is allowed as an key or value.

 HashTable:Never use it in new code. Sometimes it becomes necessary to use it to support legacy code, But never use it in new independent code.Here null is not allowed as an key or value.

Collections. synchronizedMap (Map <K,V> m):Use it in Multithreaded environment whenthere are limited number of threads and want to access code through single lock.Here null is allowed as an key or value

 ConcurrentHashMap:Use it in highly concurrent environment when number of concurrent access is very high.It permits any number of concurrent reader threads and multiple writer thread on different segment of map and so is highly scalable on highly concurrent environment. Here null is not allowed as an key or value

TreeMap :TreeMap data structure has different objective in the Map family.It keeps the data in sorted order with respect to its keys.Means sorting criteria is driven by their key.It implement SortedMap interface(which in turn extend Map interface).

TreeMap Example:-


package com.devil;

import java.util.TreeMap;

public class TreeMapExample1 {

public static void main(String args[]) {
TreeMap<String, String> treeMap = new TreeMap<String, String>();
treeMap.put("Delhi","India");
treeMap.put("Washington","USA");
treeMap.put("Beizing","China");
treeMap.put("Tokyo","Japan");
treeMap.put("Paris","France");
for (String str : treeMap.keySet()) {
String value = treeMap.get(str);
System.out.println("TreeMap Value:-" + value);
}
}

}

Output of the above code is:

TreeMap Value:-China
TreeMap Value:-India
TreeMap Value:-France
TreeMap Value:-Japan
TreeMap Value:-USA

There are two ways to define the sorting order:

  1.) Java object which are used as an key in TreeMap should implement Comparable interface and sorting logic should be put in compareTo() method. Generally we use String or Integer object(in the above example,String is used as an Key) as an key.These object already implement Comparable interface.So in that case there is no need to do that.

Example:

 Map<Person,String>treeMap=new TreeMap<Person,String>();

 Lets Person class is :

public class Person {

public String age;

public String name;

}

Here Person is used as an key so this class should implement Comparable interface.Otherwise a RunTime Exception will occur when we run the code.

2.) Passing an Comparator as an argument to the constructor of TreeMap when we create a new object.

Example: 

Map<Person,String>treeMap=new TreeMap<Person,String>(AgeComparator)

This will sort the map according to AgeComparator logic(sorting on the basis of age). Map<Person,String>treeMap=new TreeMap<Person,String>(NameComparator) This will sort the map according to AgeComparator logic(sorting on the basis ofName).More detail about Comparator and Comparable interface are in this posthttps://devilspace.org/2012/07/25/sorting-in-javacomparable-and-comparator/

TreeMap is not synchronised and so its not thread safe.We can use

Sortedmap sortedMap=Collections.SynchronizedSortedMap(new TreeMap()) to achieve thread safety in TreeMap.

Concurrent analog of TreeMap is ConcurrentSkipListMap() which should be used in highly concurrent environment.

Performance:Internally TreeMap use Red-Black Tree(a self balanced binary search tree)for storing data.Its access time(search),insert time is O(log n) as comparison to other Map implementation(all the above discussed map which are based on Hashing)which takes O(1) as look up time + O(k) time for looking in to each bucket(k is the number of element in each bucket).Generally HashMap are faster(unless we design a bad hash function).so if we do not require sorting, We should useHashMap.   So with all this, we have now got basic idea about the Map family, their usage in different situation.

 

 

How to make XSD validation in a REST based web service XML Request by using XSD file and JAXBMarshaller

Computer  Assuming we are using Jaxb2Marshaller class for marshaling/marshaling the XML request/response.Lets we want to use a xsd file named validate.xsd for validating XML REST Request.First put the validate.xsd file in to src/main/resources directory in the project workspace.Now set the JAXB configuration in your rest-servlet.xml file like:

<bean id="jaxb2Marshaller">
<property name="schema" value="classpath:/validate.xsd" />
<property name="classesToBeBound">
	<list>
<value>com.devil.space.RPCRequest</value>
<value>com.devil.space.RPCResponse</value>
</list>
</property>
</bean>

 

 

 

RPCRequest and RPCResponse are the rest request and response java xml object respectively.So the full rest-servlet.xml file would be like:

<?xml version=1.0 ?>
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:context=http://www.springframework.org/schema/context
xmlns:mvc=http://www.springframework.org/schema/mvc xmlns:util=http://www.springframework.org/schema/util
xmlns:p=http://www.springframework.org/schema/p
xsi:schemaLocation=http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd></beans>

<!-- @Controllers -->
<context:component-scan
base-package=com.devil.space.controller,com.devil.space.rest />

<bean
class=org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping >

<bean
class=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter>
<property name=messageConverters>
	<list>
<ref bean=marshallingHttpMessageConverter >
<bean
class=org.springframework.http.converter.StringHttpMessageConverter >
</list>
</property>
</bean>

<bean id=marshallingHttpMessageConverter
class=org.springframework.http.converter.xml.MarshallingHttpMessageConverter
p:marshaller-ref=jaxb2Marshaller p:unmarshaller-ref=jaxb2Marshaller >

<bean id=jaxb2Marshaller>
<property name=schema value=classpath:/validate.xsd >
<property name=classesToBeBound>
	<list>
<value<com.devil.space.RPCRequest</value>
<value<com.devil.space.RPCResponse</value>
</list>
</property>
</bean>

<bean id=viewResolver
class=org.springframework.web.servlet.view.InternalResourceViewResolver>
<property name=viewClass value=org.springframework.web.servlet.view.JstlView>
</bean>
</beans>


 

So if the xml file data is not as per xsd file validations,response message will be like :

“The request sent by the client was syntactically incorrect”

Thats it.You are done.!!

Now this message is kind of generic error message.If we want to know where exactly is the problem in our XML request,there are more things to be done:

1.Configuration in to rest-servlet.xml.

Add following configuration in to rest-servlet.xml:

<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<property name="messageConverters">
	<list>
<ref bean="marshallingHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
</list>
</property>
</bean>


 

2.Adding method for handling exception.

Lets us assume your controller class is :


@Controller
@RequestMapping("/SaveXMLData")
public class DownloadXMLDataEndPointController {

@RequestMapping(value = "/SaveAndUpdateData", method = RequestMethod.POST)
@ResponseBody
public RPCResponse saveXMLRequestData(
@RequestBody RPCRequest request) throws Exception {

----Logic for processing request-----

RPCResponse response=new RPCResponse();

--construct response object----------

return response;

}
}

In the above controller class,add another method for handling exception:

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
RPCResponse handleXMLException(HttpMessageNotReadableException ex) {

String error = "Invalid XML.Error is:-";
error = error + ex.getMessage();
String responseMessage = "FAILOVER";

RPCResponse response=new RPCResponse();

--construct response object----------

return response;
}

So the complete Controller class would be :


@Controller
@RequestMapping("/SaveXMLData")
public class DownloadXMLDataEndPointController {

@RequestMapping(value = "/SaveAndUpdateData", method = RequestMethod.POST)
@ResponseBody
public RPCResponse saveXMLRequestData(
@RequestBody RPCRequest request) throws Exception {

----Logic for processing request-----

RPCResponse response=new RPCResponse();

--construct response object----------
return response;

}

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
RPCResponse handleXMLException(HttpMessageNotReadableException ex) {

String error = "Invalid XML.Error is:-";
error = error + ex.getMessage();
String responseMessage = "FAILOVER";

RPCResponse response=new RPCResponse();

--construct response object----------

return response;
}
}

Now if we deploy the application again.And send a xml request.If there is any validation error as per our XSD file,A detail error message will be in response stating in which line in XML request is the error.

 

 

Now if there is more than one XSD files which are been used to validate more than one type of  XML request,We can configure them in single XSD file.Lets there are three XSD files (ABCD.xsd,PQRS.xsd,XYZT.xsd)for validating three types of XML request..Our validate.xsd will be as

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:include schemaLocation="ABCD.xsd" />
<xs:include schemaLocation="PQRS.xsd" />
<xs:include schemaLocation="XYZT.xsd" />
</xs:schema>


That is it.Similarly we can configure more XSD files for validating different types of XML requests.

If still there is any issue that you encounter :mail me at–    parry.ism@gmail.com

Java Object Cloning:Cloning Java Object By Using Cloneable Interface

    Coffe_Cup   Cloning means coping a object’s internal contents to a new object which will have a different memory address. Assignment operator assigns the reference or memory address to other object.Any change made in that object will reflect in original object as well.But in cloning a new object having different reference is created.And any change made in this cloned object will not make any change in original object.So essentially cloning is object duplication having different memory address.There are several ways in Java to perform object duplication or cloning like:

1.Using Java Object class’s clone() method and Cloneable iterface

2.Using Copy Constructor

3.Using Factory Method.

4.Using Serialization

In this article ,We will discuss cloning by using first approach that is by using Object class’s clone() method and Cloneable Interface.

1.Using Java Object class’s clone() method and Cloneable iterface (Cloneable is a marker interface):

In this approach, the Java Class whose object we want to clone should have implement Cloneable interface and should override object class’s clone() method.Example class for this is(CodeSample1):

package com.devil;
/*-------------------------------------------------------------------------*/
/**
* Class which implement Cloneable interface and override object class's clone()
* method and thats why its object can be used for cloning or duplication or
* copying.This class is capable of doing Shallow Cloning only.
*
*/
/*-------------------------------------------------------------------------*/
public class NationalPark implements Cloneable{
public String name;
public String stateName;
public Integer yearOfEstablishment;
public Animal animal;
public NationalPark(String name, String stateName,
Integer yearOfEstablishment) {
this.name = name;
this.stateName = stateName;
this.yearOfEstablishment = yearOfEstablishment;
Animal animal = new Animal("Tiger", 9, "Sariska");
this.animal = animal;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Integer getYearOfEstablishment() {
return yearOfEstablishment;
}
public void setYearOfEstablishment(Integer yearOfEstablishment) {
this.yearOfEstablishment = yearOfEstablishment;
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}

The above class use another class Animal whose code is as (CodeSample2)::

package com.devil;

/*-------------------------------------------------------------------------*/
/*Animal class which is not cloneable
/*-------------------------------------------------------------------------*/

public class Animal {
public String name;
public Integer age;
public String sanctuaryName;
public Animal(String name, Integer age, String sanctuaryName) {
this.name = name;
this.age = age;
this.sanctuaryName = sanctuaryName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSanctuaryName() {
return sanctuaryName;
}
public void setSanctuaryName(String sanctuaryName) {
this.sanctuaryName = sanctuaryName;
}
}

 

 

Now lets use NationalPark class for creating cloned object.Example for this demonstration is (CodeSample3)::

package com.devil;
/*-------------------------------------------------------------------------*/
/* Code example for explaining basic cloning concept
/*-------------------------------------------------------------------------*/
public class JavaCloneExample1 {

public static void main(String args[]) throws CloneNotSupportedException {

NationalPark nationalPark1= new NationalPark("Sariska","Rajashthan",1955);
NationalPark nationalPark2=nationalPark1;
NationalPark clonedNationalPark1=(NationalPark) nationalPark1.clone();

System.out.println("Are object1 and object2 have same reference:- "+(nationalPark1==nationalPark2));
System.out.println("Are object1 and clone object have same reference:- "+(nationalPark1==clonedNationalPark1));
System.out.println("");

System.out.println("NationalPark object1 hashcode:-"+""+nationalPark1.hashCode());
System.out.println("NationalPark object2 hashcode:-"+""+nationalPark2.hashCode());
System.out.println("NationalPark cloned object hashcode:-"+""+clonedNationalPark1.hashCode());
System.out.println("");
}
}

 
Output  of the above code is:
 
Are object1 and object2 have same reference:- true
Are object1 and clone object have same reference:- false

NationalPark object1 hashcode:-1068505417
NationalPark object2 hashcode:-1068505417
NationalPark cloned object hashcode:-1112287305

From the above results,Cloned object has different memory address(reference)than the original object.Also since default implementation of hashcode() method(which is in Java Object class) driven by memory address,cloned object has different hashcode than that of original object.

Now what happens if  we do not override clone() method or do not implement Cloneable interface.

Well,implementing Cloneable interface can not be avoided if we want to give our class cloning capability.Lets we are not implementing Cloneable  interface in our NationalPark class(CodeSample1) and now we are trying to run our programme CodeSample3 ,Following exception will occur in the output:

java.lang.CloneNotSupportedException: com.devil.NationalPark
at java.lang.Object.clone(Native Method)
at com.devil.NationalPark.clone(NationalPark.java:30)
at com.devil.JavaCloneExample1.main(JavaCloneExample1.java:11)

Now,overriding clone() method can be avoided but of no use.It will be like we have something but we can not use.Its because if we are not overriding clone() method,It means we are using Java Object’s clone() method whose accessibility is “protected”.That means we can use this method only in the child class(in our case:NationalPark) whose base class in Object.If we will try to access this method outside(lets say in CodeSample3) of cloned class (NationalPark),

a compile error will come up saying :-”The method clone() from the type Object is not visible”.

So essence is that,Its completely necessary to implement Clone able interface for making  a class capable of cloning.And its necessary to override clone() method so that we can use cloning capability of class.

 

Now Java Cloning is of two types;Shallow copy and Deep copy which are explained as below

Shallow Copying :

Now if a java object(say NationalPark in our case) contains a reference of other objects (say Animal in our case) as well.The default cloning(as in above example) will not clone internal object(animal).Animal object reference will be same in cloned object(clonedNationalPark1) and original object(nationalPark1).So  any change made in animal object in Cloned Object will be reflected in animal object of Original Object also.This is called Shallow Copying.An example showing Shallow Copying is as:

package com.devil;
/*-------------------------------------------------------------------------*/
/* This Cloning Example demonstrates Shallow Copy
*
*
/*-------------------------------------------------------------------------*/
public class JavaCloneExample2 {
public static void main(String args[]) throws CloneNotSupportedException {
NationalPark nationalPark1= new NationalPark("Sariska","Rajashthan",1955);
NationalPark nationalPark2=nationalPark1;
NationalPark clonedNationalPark1=(NationalPark) nationalPark1.clone();
System.out.println("NationalPark object1:-"+nationalPark1.hashCode());
System.out.println("NationalPark object2:-"+nationalPark2.hashCode());
System.out.println("NationalPark cloned object:-"+clonedNationalPark1.hashCode());
System.out.println("");
Animal animal1=nationalPark1.getAnimal();
Animal animal2=clonedNationalPark1.getAnimal();
System.out.println("Are animal1 and animal2 have same reference:- "+(animal1==animal2));
System.out.println("");
//Any change in animal2 object will reflect in animal1 object as well.
animal2.setName("Elephant");
animal2.setSanctuaryName("Kajiranga");
System.out.println("NationalPark animal2 object attributes:- "+animal2.getName()+"--"+
animal2.getSanctuaryName()+"--"+animal2.getAge());
System.out.println("NationalPark animal1 object attributes:- "+animal1.getName()+"--"+
animal1.getSanctuaryName()+"--"+animal1.getAge());
}
}

The output of the above code will be as:

 

NationalPark object1:-1489230252
NationalPark object2:-1489230252
NationalPark cloned object:-570939579

Are animal1 and animal2 have same reference:- true

NationalPark animal2 object attributes:- Elephant--Kajiranga--9
NationalPark animal1 object attributes:- Elephant--Kajiranga--9

So in shallow coping internal object animal1 of original object(e.g nationalPark1) and internal object animal2 of cloned object(e.g clonedNationalPark1) points to the same memory reference.Any change made to animal2 object will reflect in animal1 object as well.So if we want to manipulate internal objects of cloned object and do not want to affect original object, we should choose Deep Copying cloning.

Deep Copying:

In Deep Copying all the internal objects which are used as an reference(e.g Animal) will also cloned with that of original object(e.g NationalPark).So in deep copying we will get a complete cloned object which can be changed anyhow without affecting the original object.If we want  a deep copy of cloned object,Following things should be keep in mind:

1. All the internal object which are used as an reference (e.g Animal) should implement Cloneable interface.

2.All the internal objects which are used as an reference (e.g Animal)should override clone()

method of Java Object class.

 

So w.r.t above example,If we want to make Deep Cloning of NationalPark object.We have to change Animal class as per above two points which will be as:

package com.devil;
/*-------------------------------------------------------------------------*/
/* Animal class which is Cloneable
/*-------------------------------------------------------------------------*/
public class Animal implements Cloneable {
public String name;
public Integer age;
public String sanctuaryName;
public Animal(String name, Integer age, String sanctuaryName) {
this.name = name;
this.age = age;
this.sanctuaryName = sanctuaryName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSanctuaryName() {
return sanctuaryName;
}
public void setSanctuaryName(String sanctuaryName) {
this.sanctuaryName = sanctuaryName;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
 
Last step will be to make change in Clone() method of the original object (NationalPark) so that internal objects are also cloneable.So the modified NationalPark class(only change is in clone() method) will be as:
 
package com.devil;
/*-------------------------------------------------------------------------*/
/*
* Class which implement Cloneable interface and override object class's clone()
* method and thats why its object can be used for cloning or duplication or
* copying.This Class is capable of doing Deep Cloning
*
*/
/*-------------------------------------------------------------------------*/
public class NationalPark implements Cloneable {
public String name;
public String stateName;
public Integer yearOfEstablishment;
public Animal animal;
public NationalPark(String name,String stateName,Integer yearOfEstablishment){
this.name=name;
this.stateName=stateName;
this.yearOfEstablishment=yearOfEstablishment;
Animal animal=new Animal("Tiger",9,"Sariska");
this.animal=animal;
}
//Clone() method implementation for Deep Cloning
@Override
protected Object clone() {
try {
NationalPark nationalPark= (NationalPark) super.clone();
nationalPark.animal=(Animal) this.animal.clone();
return nationalPark;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Integer getYearOfEstablishment() {
return yearOfEstablishment;
}
public void setYearOfEstablishment(Integer yearOfEstablishment) {
this.yearOfEstablishment = yearOfEstablishment;
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
Below example demonstrate Deep Copying by using above class:
 
 
package com.devil;
/*------------------------------------------------------------------------------*/
/* This Cloning Example demonstrates Deep Copy
*
*
/*-----------------------------------------------------------------------------*/
public class JavaCloneExample3 {
public static void main(String args[]) throws CloneNotSupportedException {
NationalPark nationalPark1= new NationalPark("Sariska","Rajashthan",1955);
NationalPark nationalPark2=nationalPark1;
NationalPark clonedNationalPark1=(NationalPark) nationalPark1.clone();
System.out.println("Are object1 and object2 have same reference:- "+
(nationalPark1==nationalPark2));
System.out.println("Are object1 and clone object have same reference:- "+
(nationalPark1==clonedNationalPark1));
System.out.println("");

System.out.println("NationalPark object1:-"+nationalPark1.hashCode());
System.out.println("NationalPark object2:-"+nationalPark2.hashCode());
System.out.println("NationalPark cloned object:-"+clonedNationalPark1.hashCode());
System.out.println("");

Animal animal1=nationalPark1.getAnimal();
Animal animal2=clonedNationalPark1.getAnimal();
System.out.println("Are animal1 and animal2 have same reference:- "+(animal1==animal2));

System.out.println("");
//Any change in animal2 object will not reflect in animal1 object.
animal2.setName("Elephant");
animal2.setSanctuaryName("Kajiranga");
System.out.println("NationalPark animal2 object attributes:- "+animal2.getName()+"--"+
animal2.getSanctuaryName()+"--"+animal2.getAge());
System.out.println("NationalPark animal1 object attributes:- "+animal1.getName()+"--"+
animal1.getSanctuaryName()+"--"+animal1.getAge());
}
}

 

Output of the above code is as:

Are object1 and object2 have same reference:- true
Are object1 and clone object have same reference:- false

NationalPark object1:-1004958336
NationalPark object2:-1004958336
NationalPark cloned object:-375869497

Are animal1 and animal2 have same reference:- false

NationalPark animal2 object attributes:- Elephant--Kajiranga--9
NationalPark animal1 object attributes:- Tiger--Sariska--9
Above output clearly shows that animal1 and animal2 are having difference memory reference.Any change made in the animal2 object will not affect animal1 object and so original NationalPark object .So this was the Deep Copying.
 
One of the major application of using cloned object is for creating defensive copy in designing  of a immutable class.
 
 
So after reading this article ,you should be able to know the answer for the following questions:
 
1.What is Java Object Cloning or Java Cloning.And what is its uses ?

2.What is the use of Java Object clone() method.?

3.What is the use of Cloneable interface?

4.What is Shallow Cloning (or Shallow Copy) and Deep Cloning(or Deep Copy).?
What is the difference between these two types of cloning.?

5.When we should use Shallow Copy and when we should use Deep Copy.?

Internals of Comparable and Comparator Interface

Sorting in Java:Comparable and Comparator Interface

One of the most important aspect of every programming language is Sorting. Sorting of Java objects is also becomes  desirable sometimes.In Java,we can get sorted objects by using Comparable or  Comparator interface.

By using Comparable interface:

Comparable interface is one of the most basic entity provided in Java used for sorting.This interface has only one method defined.

public int compareTo(Object o).

There are two steps for getting a sorted list of object.

1.Every class whose object we want to sort should implement this interface and compareTo (Object o) method should be overridden in all the implemented classes.

2.Pass the list of object to a Collections.sort(List list).We will get list of sorted object.

All the basic class like String,Integer,Float,Date implements this interface.So first step is already done.Below example demonstrate this:

package com.devil.space;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingWithComparableExample1 {
	public static void main(String args[]) {
		List<String>animalNameList = new ArrayList<String>();
		animalNameList.add("Tiger");
		animalNameList.add("Lion");
		animalNameList.add("Deer");
		animalNameList.add("Horse");
		Collections.sort(animalNameList);
		for (String name : animalNameList) {
			System.out.println("Animal Name is :- " + name);
		}
	}

}

output of the above code is:

Animal Name is :- Deer
Animal Name is :- Horse
Animal Name is :- Lion
Animal Name is :- Tiger

So here a list of String objects is sorted

Now if we want to sort an object w.r.t some attribute. We can use either Comparable

interface or Comparator interface.Lets Animal is the class whose object we want to sort.

package com.devil.space;

public class Animal implements Comparable<Animal> {

	public String name;
	public Integer age;
	public String sanctuaryName;

	public Animal(String name, Integer age, String sanctuaryName) {
		this.name = name;
		this.age = age;
		this.sanctuaryName = sanctuaryName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getSanctuaryName() {
		return sanctuaryName;
	}

	public void setSanctuaryName(String sanctuaryName) {
		this.sanctuaryName = sanctuaryName;
	}

	@Override
	public int compareTo(Animal o) {
		 return (this.name.compareTo(o.name));
		//return this.age.compareTo(o.age);
		//return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

}

package com.devil.space;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingWithComparableExample2 {
	public static void main(String args[]) {
		List<Animal> animalList = new ArrayList<Animal>();
		Animal animal1 = new Animal("Horse", 7,"Corbett");
		Animal animal2 = new Animal("Elephant", 12,"Kajiranga");
		Animal animal3 = new Animal("Tiger", 9, "Ranthambhor");
		animalList.add(animal1);
		animalList.add(animal2);
		animalList.add(animal3);
		Collections.sort(animalList);
		for(Animal animal:animalList){
			System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
		}

	}
}

Output of the above code will be:

Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9—Ranthambhor

Here Animal objects are sorted according to ‘name’ attribute.

Now comment the  line no 41 and remove comment from line no 42 like:

public int compareTo(Animal o) {
		 //return (this.name.compareTo(o.name));
		return this.age.compareTo(o.age);
		//return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

Now output of the SortingWithComparableExample2 will be:

Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor
Animal attributes are: Elephant–12—Kajiranga

Here Animal objects are sorted according to ‘age’ attribute.

Similarly now comment the  line no 42 and remove comment from line no 43  like:

public int compareTo(Animal o) {
		 //return (this.name.compareTo(o.name));
		//return this.age.compareTo(o.age);
		return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

Now output of the SortingWithComparableExample2 will be:

Animal attributes are: Horse–7–Corbett
Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Tiger–9—Ranthambhor

Here Animal objects are sorted according to ‘sanctuaryName’ attribute.

Now one point can crop up in mind in how  string1.compareTo(String string2)

works internally like line 41,42,43 in Animal Class.Well,it uses lexical order or alphabetically

order for sorting.We can see String class source code to see the exact implementation.

By using Comparator interface:

There are two steps for getting a sorted list of object.

1.First write an Comparator implementation and put our sorting logic in to public int compare(Object o1,Object2) method

2.Pass the list of objects and comparator implementation to  Collections.sort(List list,new NameComparator).We will get list of sorted object.

For the above Animal class example,lets define three Comparator.

1.NameComparator

2.AgeComparator

3.SanctuaryNameComparator

package com.devil.space;

import java.util.Comparator;

public class NameComparator implements Comparator<Animal>{

	@Override
	public int compare(Animal o1, Animal o2) {

		return o1.getName().compareTo(o2.getName());
	}

}
package com.devil.space;

import java.util.Comparator;

public class AgeComparator implements Comparator<Animal> {

	@Override
	public int compare(Animal o1, Animal o2) {
		return o1.getAge().compareTo(o2.getAge());
	}

}
package com.devil.space;

import java.util.Comparator;

public class SanctuaryNameComparator implements Comparator<Animal>{

	@Override
	public int compare(Animal o1, Animal o2) {
		return o1.getSanctuaryName().compareTo(o2.getSanctuaryName());
	}

}

Now lets see how we will use these Comparator:

package com.devil.space;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingWithComparatorExample {
		public static void main(String args[]) {
			List<Animal> animalList = new ArrayList<Animal>();
			Animal animal1 = new Animal("Horse", 7, "Corbett");
			Animal animal2 = new Animal("Elephant", 12,"Kajiranga");
			Animal animal3 = new Animal("Tiger", 9,"Ranthambhor");
			animalList.add(animal1);
			animalList.add(animal2);
			animalList.add(animal3);
			Collections.sort(animalList,new NameComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}
			System.out.println("");
			Collections.sort(animalList,new AgeComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}
			System.out.println("");
			Collections.sort(animalList,new SanctuaryNameComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}

	}
}

Output of the above code will be:

Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor

Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor
Animal attributes are: Elephant–12–Kajiranga

Animal attributes are: Horse–7–Corbett
Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Tiger–9—Ranthambhor

Three set of output are according to which Comparator class we have passed in the Collection.sort()method with the list of objects.First set is sorted according to name,second set is sorted  according to age,third set is sorted according to sanctuaryName.

One thing that we can notice is that in compare(Object o1,Object o2)method,when we put sorting logic of some string,we use compareTo(String s1) .So we can say Comparator is kind

of utility interface whose implementation uses Comparable interface implementation internally

(that is why Comparator is in java.util package and Comparable is in java.lang package).

So lets sum up points:

What is the  difference between Comparable and Comparator interface.

1.WithComparable interface ,we can sort the objects on the basis of one criteria only.

With Comparator,we can get different sorted list on the basis of different sort criteria.

2.With Comparable, we put sorting logic in compareTo() method which needs one parameter,With Camparator,we put sorting logic in compare() which needs two parameter

3.With Comparable interface,developer pass only list of object to Collections.sort (list)method.With Comparator,developer needs to pass a comparator implementation as well,

Like Collections.sort(list,new AgeComparator());

4.Comparable interface is java.lan pacakge and Comparator is in java.util package.