Monday 17 November 2014

What is static and dynamic class loading in Java?

Static Class Loading: Creating objects and instance using new keyword is known as static class loading. The retrieval of class definition and instantiation of the object is done at compile time.

Using new operator you load classes statically in java.

public static void main(String[] args)
{
 Sample m = new Sample();
}

Dynamic Class Loading: Dynamic class loading is done when the name of the class is not known at compile time. Dynamic class loading also called as reflection.This can be achieved by invoking the Class loader functions programmatically. Typically we use Class.forName(String className) to get the class first and then we will call the newInstance() method on the returned class to get the instance.

For example if you want to get a instance of Sample class using dynamic class loading, you have to ...
Sample sample = null;
Class sampleClass = Class.forName("com.sample.Sample");
sample = (Sample) sampleClass.newInstance();
sample.doSomeThing();
Here in dynamic class loading ClassNotFoundException can be thrown if given Class loader doesn’t find the given Class name (com.sample.Sample) in the classpath. Class Loader looks for a given class in following sequence:

  • The forName(..) method in the class called Class
  • The findSystemClass(..) method in the class class called ClassLoader
  • The loadClass(..) method in the class called ClassLoader

Tuesday 28 October 2014

Java Class Loaders

        Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.



Classloaders and their explaination -  
  • Bootstrap (primordial) - No Loads JDK internal classes, java.* packages. (as defined in the  sun.boot.class.path system property, typically loads rt.jar and i18n.jar). Classes loaded by Bootstrap  class loader have no visibility into classes loaded by its descendants (i.e. Extensions and Systems  class loaders).

  • Extensions - Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
  • System - No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options). The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).


Monday 27 October 2014

Tomcat HTTP to HTTPS redirect

The following post shows how to easily redirect HTTP to HTTPS in Tomcat servlet container that it always requires secure connection. It was assumed that the following TCP ports are used for that purpose:

8080: for HTTP
8443: for HTTPS


  • Edit you server.xml file located in conf folder of tomcat installation directory

<Connector port="8080" protocol="HTTP/1.1"
     redirectPort="443"/>

<Connector port="8443" protocol="HTTP/1.1"
    SSLEnabled="true"
    scheme="https" secure="true"
    clientAuth="false"
    sslProtocol="TLS"
    keystoreFile="conf/keystore"
    keystorePass="s00perSeeekrit"/>

  • Add below entry in web.xml of your tomcat conf folder.
<security-constraint>
     <web-resource-collection/>
         <web-resource-name>HTTPSOnly</web-resource-name>
         <url-pattern>/*</url-pattern
     </web-resource-collection>
     <user-data-constraint>
         <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
</security-constraint>
  • Restart Tomcat.
You're done! The Tomcat always requires secure connection now...

Friday 24 October 2014

Singleton Design Pattern in java

This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.


There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

Implementing Singletons:


The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:
// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}
Here is the main program file where we will create singleton object:
// File Name: SingletonDemo.javapublic class SingletonDemo {
   public static void main(String[] args) {
      Singletontmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}
This would produce the following result:
demoMethod for singleton


Interview Questions & Answers on singleton class:


Question: What is double checked locking in Singleton?
Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public static Singleton getInstance(){
     
if(_INSTANCE == null){
         
synchronized(Singleton.class){
         
//double checked locking - because second check of Singleton instance with lock
                
if(_INSTANCE == null){
                    _INSTANCE = 
new Singleton();
                
}
            
}
         
}
     
return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.


Question: How do you prevent for creating another instance of Singleton using clone() method?
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.


Question: What is lazy and early loading of Singleton and how will you implement it?
Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.


If you have 

Wednesday 22 October 2014

hashCode() and equals() methods in java

Usage of hashCode() and equals()
hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.

equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.


Overriding the default behavior
Everything works fine until you do not override any of these methods in your classes. But, sometimes application needs to change the default behavior of some objects.

Lets take an example where your application has Employee object. Lets create a minimal possible structure of Employee class

public class Employee
{
    private Integer id;
    private String firstname;
    private String lastName;
    private String department;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
}
Above Employee class has some very basic attributes and there accessor methods. Now consider a simple situation where you need to compare two employee objects.
public class EqualsTest {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        e1.setId(100);
        e2.setId(100);
        //Prints false in console
        System.out.println(e1.equals(e2));
    }
}
Above method will print “false“. But, is it really correct after knowing that both objects represent same employee. In a real time application, this must return true.

To achieve correct behavior, we need to override equals method as below:
public boolean equals(Object o) {
        if(o == null)
        {
            return false;
        }
        if (o == this)
        {
           return true;
        }
        if (getClass() != o.getClass())
        {
            return false;
        }
        Employee e = (Employee) o;
        return (this.getId() == e.getId());
}
Add this method to your Employee class, and EqualsTest will start returning “true“.

So are we done? Not yet. Lets test again above modified Employee class in different way.
import java.util.HashSet;
import java.util.Set;

public class EqualsTest
{
    public static void main(String[] args)
    {
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        e1.setId(100);
        e2.setId(100);

        //Prints 'true'
        System.out.println(e1.equals(e2));

        Set employees = new HashSet();
        employees.add(e1);
        employees.add(e2);
        //Prints two objects
        System.out.println(employees);
    }
}
Above class prints two objects in second print statement. If both employee objects have been equal, in a Set which stores only unique objects, there must be only one instance inside HashSet, after all both objects refer to same employee. What is it we are missing??

We are missing the second important method hashCode(). As java docs say, if you override equals() method then you must override hashCode() method. So lets add another method in our Employee class.
@Override
 public int hashCode()
 {
    final int PRIME = 31;
    int result = 1;
    result = PRIME * result + getId();
    return result;
 }
Once above method is added in Employee class, the second statement start printing only single object in second statement, and thus validating the true equality of e1 and e2.

Key Points
  • Always use same attributes of an object to generate hashCode() and equals() both. As in our case, we have used employee id.
  • equals() must be consistent (if the objects are not modified, then it must keep returning the same value).
  • Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
  • If you override one, then you should override the other.
If you feel, I am missing something or wrong somewhere, please leave a comment. I will update this post again to help others.

Hashmap in Java

If anybody asks me to describe “How HashMap works?“, I simply answer: “On principle of Hashing“. HashMap is a Collection which works on principle of Hashing and it uses key and value pairs to store the information and we can get the value if we pass key to the HashMap. You can also say HashMap is fast as it is not synchronized.

HashMap class comes from java.util package and HashMap class extends AbstractMap and implements Map, Cloneable and Serializable interfaces. HashMap is nothing but Hash table based implementation of Map Interface.



What is Hashing

Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

A little about Entry class

A map by definition is : “An object that maps keys to values”. Very easy.. right?
So, there must be some mechanism in HashMap to store this key value pair. Answer is YES. HashMap has an inner class Entry, which looks like this:

static class Entry implements Map.Entry{
          final K key;
          V value;
          Entry next;
          final int hash;
          ...
}

Surely Entry class has key and value mapping stored as attributes. Key has been marked as final and two more fields are there: next and hash.


put() method in hashmap

We need to pass Key and Value object to put() method in Java HashMap. Once we pass the key and value to in put() method of HashMap, HashMap calls hashCode method on key object and use hashcode into own hashing function to find the bucket location. Bucket is the place where Entry object is stored and hashcode is like an address of that bucket. So what exactly we store in bucket? This is very important to understand. Java stores both Key and Value object as a Map.Entry in bucket. These are stored like LinkedList. But why these are stored as LinkedList. As we know we are using the hashcode to find the bucket location but two unequal objects can have same hashcode. So there are chances of collision. So along with value key is stored.


get() methods in hashmap

We need to pass key to the get method which takes the key as an argument and try to find bucket position using the hashcode. Once it finds the bucket using equals function it gets the value and returns it.

If no match is found, get() method returns null.


Key Notes


  • Data structure to store Entry objects is an array named table of type Entry.
  • A particular index location in array is referred as bucket, because it can hold the first element of a LinkedList of Entry objects.
  • Key object’s hashCode() is required to calculate the index location of Entry object.
  • Key object’s equals() method is used to maintain uniqueness of Keys in map.
  • Value object’s hashCode() and equals() method are not used in HashMap’s get() and put() methods.
  • Hash code for null keys is always zero, and such Entry object is always stored in zero index in Entry[].
  • Order in not maintained in hashmap.


What is the load factor in java HashMap and what happens when size of the HashMap exceeds a given threshold defined by load factor?

Load factor of HashMap is is .75 it will act to re-size the map once it filled 75%, so once size exceeds 75%, then Java HashMap re-size itself by creating a new bucket array of size twice of size defined previously for the HashMap ,then it start putting every old element into that new bucket array. This process is also called rehashing because hash function is used to find the new bucket location.

What are the differences between HashMap and Hashtable?

Lets see what are the differences we can see in HashMap and Hashtable.

1. Synchronization :
Hashtables are synchronized , it means at one point of time only one thread can modify a Hashtable. i.e any thread before performing an update on a hashtable will be acquiring a lock on the object while others will wait for lock to be released.
Hashmap is not synchronized , but we can make it synchronized.

2. Fail-safe:
Iterator of HashMap is fail-safe but the enumerator for the Hashtable is not fail-safe. Lets see what exactly fail-safe is. If an iterator has been created on a collection object and some other thread tries to modify this object , a concurrent modification exception will be thrown. So fail safe is like ability of system to fail but it wont produce some catastrophic results.

3. null values
Hashtable doesn’t allow null but Hashmap allows null values.

Hibernate Entity / Persistence LifeCycle States

As you know that Hibernate works with normal Java objects that your application creates with the new operator. In raw form (without annotations), hibernate will not be able to identify your java classes, but when they are properly annotated with required annotations then hibernate will be able to identify them and then work with them e.g. store in DB, update them etc. These objects can be said to mapped with hibernate.

Given an instance of an object that is mapped to Hibernate, it can be in any one of four different states: transient, persistent, detached or removed.

Transient Object

Transient objects exist in heap memory. Hibernate does not manage transient objects or persist changes to transient objects.
Transient objects are independent of Hibernate
Transient objects are independent of Hibernate
To persist the changes to a transient object, you would have to ask the session to save the transient object to the database, at which point Hibernate assigns the object an identifier and marks the object as being in persistent state.

Persistent Object

Persistent objects exist in the database, and Hibernate manages the persistence for persistent objects.
Persistent objects are maintained by Hibernate
Persistent objects are maintained by Hibernate
If fields or properties change on a persistent object, Hibernate will keep the database representation up to date when the application marks the changes as to be committed.

Detached Object

Detached objects have a representation in the database, but changes to the object will not be reflected in the database, and vice-versa. This temporary separation of the object and the database is shown in image below.
Detached objects exist in the database but are not maintained by Hibernate
Detached objects exist in the database but are not maintained by Hibernate
A detached object can be created by closing the session that it was associated with, or by evicting it from the session with a call to the session’s evict() method.
In order to persist changes made to a detached object, the application must reattach it to a valid Hibernate session. A detached instance can be associated with a new Hibernate session when your application calls one of the load, refresh, merge, update(), or save() methods on the new session with a reference to the detached object. After the call, the detached object would be a persistent object managed by the new Hibernate session.

Removed Object

Removed objects are objects that are being managed by Hibernate (persistent objects, in other words) that have been passed to the session’s remove() method. When the application marks the changes held in the session as to be committed, the entries in the database that correspond to removed objects are deleted.

Key Points

  1. Newly created POJO object will be in the transient state. Transient object doesn’t represent any row of the database i.e. not associated with any session object. It’s plain simple java object.
  2. Persistent object represent one row of the database and always associated with some unique hibernate session. Changes to persistent objects are tracked by hibernate and are saved into database when commit call happen.
  3. Detached objects are those who were once persistent in past, and now they are no longer persistent. To persist changes done in detached objects, you must reattach them to hibernate session.
  4. Removed objects are persistent objects that have been passed to the session’s remove() method and soon will be deleted as soon as changes held in the session will be committed to database.

Tuesday 21 October 2014

Hibernate - How to fix “identifier of an instance altered from X to Y”?

Problem :- Getting the error ” identifier of an instance of com.sample.SampleAltered from 1 to 1″

Solution :- Check whether the java type of the identifier field in the Data Object, the type of the field in the hibernate xml file and the type of the column in the database are compatible types or not.

Explanation :-
This problem will occure only when you have an mismatch of data type between your bean-hibername xml mapping & database table column datatype.

For Example,

class SampleAltered{

long sampleId;
String sampleName;


public int getSampleId(){
….
}

public void setSampleId(int i){
…..
}

}

And this was the hbm file declaration

<class name="com.sample.SampleAltered" table="sample_data">
   <id name=”sampleId” type=”int” column=”sample_id”>
       <generator class=”native” />
   </id>
   <property name=”sampleName” type=”string” column=”sample_name” length=”50″/>
</class>


In above example if you note, class SampleAltered was having sampleId with datatype long & hbm xml file contains the entry for same with datatype int.

Whenever you are trying to do database transaction with above mapping you will get the error of "identifier of an instance altered from X to Y".

To fix this issue you need to change datatype of sampleId either in hbm mapping file or in class.

Java Collections Framework

Collections

A data structure is a collection of data organized in some fashion. The structure not only stores data but also supports operations for accessing and manipulating the data. The java.util package contains one of Java’s most powerful subsystems: The Collections Framework. The Collections Framework is a sophisticated hierarchy of interfaces and classes that provide state-of-the-art technology for managing groups of objects.

So What Do You Do with a Collection?

There are a few basic operations you'll normally use with collections
  • Add objects to the collection.
  • Remove objects from the collection.
  • Find out if an object (or group of objects) is in the collection.
  • Retrieve an object from the collection (without removing it).
  • Iterate through the collection, looking at each element (object) one after another.
  • Key Interfaces and Classes of the Collections Framework 
The collections API begins with a group of interfaces, but also gives you a truckload of concrete classes.

MapsSetsListsQueuesUtilities
HashMapHashSetArrayListPriorityQueueCollections
HashtableLinkedHashSetVectorArrays
TreeMapTreeSetLinkedList
LinkedHashMap

The interface and class hierarchy for collections




Collections come in four basic flavors:
  • Lists Lists of things (classes that implement List). 
  • Sets Unique things (classes that implement Set). 
  • Maps Things with a unique ID (classes that implement Map). 
  • Queues Things arranged by the order in which they are to be processed. 

Ordered When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.

Sorted A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order.

List Interface
A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. The three List implementations are described in the following sections.

1 . ArrayList Think of this as a growable array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted. You might want to know that as of version 1.4, ArrayList now implements the new RandomAccess interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant time) random access." Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.

2 . Vector Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two original collections, the rest were added with Java 2 versions 1.2 and 1.4. A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. You'll normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector is the only class other than ArrayList to implement RandomAccess.

3. LinkedList A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek(), poll(), and offer().

Set Interface
A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals() method determines whether two objects are identical (in which case only one can be in the set). The three Set implementations are described in the following sections.

1. HashSet A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

2. LinkedHashSet A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

3. TreeSet The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. You're probably quite familiar with Maps since many languages support data structures that use a key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

1. HashMap The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashCode() implementation, the better access performance you'll get.HashMap allows one null key and multiple null values in a collection.

2. Hashtable Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming inconsistency: HashMap vs. Hashtable. Where's the capitalization of t? Oh well, you won't be expected to spell it. Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

3. LinkedHashMap Like its Set counterpart, LinkedHashSet, the LinkedHash-Map collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

4. TreeMap You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered.

Queue Interface
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

1. PriorityQueue This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.


Basic Features of Main Interfaces
Core collection interfaces are the base to Java Collections framework. They include the interfaces Collection, Set, List, Queue and Map on which all the data structures are built.
  1. Collection is the root interface for all the hierarchy (except Map).
  2. Set interface unique feature is that it does not accept duplicate elements. That is, no two elements will be the same.
  3. SortedSet interface is derived from Set interface and adds one more feature that the elements are arranged in sorted order by default.
  4. List interface permits duplicate elements.
  5. Queue interface holds elements and returns in FIFO order.
  6. Map adds the elements in key/value pairs. Duplicate keys are not allowed, but duplicate values are allowed. One key can map one value only.
  7. SortedMap interface is a particular case of Map. Keys are sorted by default.

How Clone method works in JAVA...???

What is clone of object in Java

An object which is returned by clone() method is known as clone of original instance. A clone object should follow basic characteristics e.g. a.clone() != a, which means original and clone are two separate object in Java heap, a.clone().getClass() == a.getClass() and clone.equals(a), which means clone is exact copy of original object. These characteristic is followed by a well behaved, correctly overridden clone() method in Java, but it's not enforced by cloning mechanism. Which means, an object returned by clone() method may violate any of these rules. By following convention of returning object by calling super.clone(), when overriding clone() method, you can ensure that it follows first two characteristics. In order to follow third characteristic, you must override equals method to enforce logical comparison, instead of physical comparison exists in java.lang.Object. For example, clone() method of Rectangle class in this method return object, which has these characteristics, but if you run same program by commenting equals(), you will see that third invariant i.e. clone.equals(a) will return false. By the way there are couple of good items on Effective Java regarding effective use of clone method, I highly recommend to read those items after going through this article.

How Clone method works in Java

java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so implemented in native code. Since it's convention to return clone() of object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method. This method, first checks if corresponding object implements Cloneableinterface, which is a marker interface. If that instance doesn't implements Cloneable then it throws CloneNotSupported in Java, a checked exception, which is always required to be handled while cloning an object. If object pass this check, than java.lang.Object's clone() method creates a shallow copy of object and returned it to the caller. Since Object class' clone() method creates copy by creating new instance, and then copying field-by-field, similar to assignment operator, it's fine for primitives and Immutable object, but not suited if your class contains some mutable data-structure e.g. Collection classes like ArrayList or arrays. In that case, both original object and copy of object will point to the same object in heap. You can prevent this by using technique known as deep cloning, on which each mutable field is cloned separately. In short, here is how clone method works in Java :

1) Any class calls clone() method on instance, which implements Cloneable and overrides protected clone() method from Object class, to create a copy.

  Rectangle rec = new Rectangle(3060);
  logger.info(rec);
      
    try {
         logger.info("Creating Copy of this object using Clone method");
         Rectangle copy = rec.clone();
         logger.info("Copy " + copy);
          
    } catch (CloneNotSupportedException ex) {
         logger.debug("Cloning is not supported for this object");
    }

2) Call to clone() method on Rectangle is delegated to super.clone(), which can be a custom super class or by default java.lang.Object

    @Override
    protected Rectangle clone() throws CloneNotSupportedException {
        return (Rectangle) super.clone();
    }

3) Eventually call reaches to java.lang.Object's clone() method, which verify if corresponding instance implements Cloneable interface, if not then it throws CloneNotSupportedException, otherwise it creates a field-by-field copy of instance of that class and returned to caller.

So in order for clone() method to work properly, two things need to happen, a Class should implement Cloneable interface and should override clone() method of Object class. By the way this was the simplest example of overriding clone method and how it works, things gets more complicated with real object, which contains mutable fields, arrays, collections, Immutable object and primitives.

Key Points to remember...

  1. Clone method is used to create a copy of object in Java. In order to use clone() method, class must implement java.lang.Cloneable interface and override protected clone() method from java.lang.Object. A call to clone() method will result in CloneNotSupportedException, if that class doesn't implement Cloneable interface.
  2. No constructor is called during cloning of Object in Java.
  3. Default implementation of clone() method in Java provides "shallow copy" of object, because it creates copy of Object by creating new instance and then copying content by assignment, which means if your Class contains a mutable field, then both original object and clone will refer to same internal object. This can be dangerous, because any change made on that mutable field will reflect in both original and copy object. In order to avoid this, override clone() method to provide deep copy of object.

Java - Exception Hierarchy

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.





All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using thethrow keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}
For more info about throw click here

The finally Keyword:

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}