Home > DeveloperSection > Forums > How do I copy an object in Java?
Pooja Malohtra
Pooja Malohtra

Total Post:47

Posted on    July-24-2015 11:54 PM

 Java Java 

 1 Reply(s)
 714  View(s)
Rate this:
DummyBean dum = new DummyBean();
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the 'dum' to dumtwo' and I want to change 'dum' without affecting the 'dumtwo'. But the above code is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of 'dum' and assign it to 'dumtwo' ?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    July-25-2015 8:26 AM

public class Deletable implements Cloneable{
    private String str;
    public Deletable(){
    public void setStr(String str){
        this.str = str;
    public void display(){
        System.out.println("The String is "+str);
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
and wherever you want to get another object, simple perform cloning. e.g:

Deletable del = new Deletable();
Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                 // object, the changes made to this object will
                                 // not be reflected to other object

In your case object is copied as a shallow copy, but if you need independent object you need to clone this object as deep copy.

Don't want to miss updates? Please click the below button!

Follow MindStick