1600 PMP mock questions 1400 CAPM mock questions 800 SCJP 6 mock questions 600 OCAJP 7 mock questions 590 OCPJP 7 mock questions 556 SCWCD 5 mock questions 500 OCEJWCD 6 mock questions pdfDownload (java,struts, hibernet etc)

Java Tutorials

What is difference between shallow copy and deep copy ?

Only instances of classes that implement the Cloneable interface can be cloned. Trying to clone an object that does not implement the Cloneable interface throws a CloneNotSupportedException. Both shallow copy and deep copy object nedd to implement Cloneable Interface.

Shallow copy :
The java.lang.Object root superclass defines a clone() method.
default behavior of clone() is to return a shallow copy of the object. This means that the values of all of the original object?s fields are copied to the fields of the new object.
If a shallow copy is performed on obj1, then it is copied but its contained objects are not.
For Example:
Public class Emp
Private Address address;
Emp emp1 = new Emp();
Address add = new Address();
emp1. address= add.

If we clone
Emp emp2 = emp1.clone();
Then emp2.addess reference to the same Address object which emp1 refer.

Deep Copy :
A deep copy occurs when an object is copied along with the objects to which it refers.
A deep copy makes a distinct copy of each of the object?s fields, recursing through the entire graph of other objects referenced by the object being copied. The Java API provides no deep-copy equivalent to Object.clone(). One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes.
Your Object Class should implements Serializable and Cloneable interface. .
public static Object copy(Object orig) {

Object obj = null;

try {

// Write the object out to a byte array

ByteArrayOutputStream bo = new ByteArrayOutputStream();

ObjectOutputStream out = new ObjectOutputStream(bo);




// Make an input stream from the byte array and read

// a copy of the object back in.

ObjectInputStream in = new ObjectInputStream(

new ByteArrayInputStream(bos.toByteArray()));

obj = in.readObject();


catch(IOException e) {



catch(ClassNotFoundException cnfe) {



return obj;


Reviews and Comments

PMP, CAPM, PMI is a registered certification mark of the Project Management Institute, Inc

Copyright © www.techfaq360.com 2019

About US | Contact US | Privacy Policy | Terms and Conditions  | Website disclaimer  | Cancellation and Refund Policy  | Shipping & Delivery Policy