Interview Questions

Tracking Memory Leaks in Java

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

Tracking Memory Leaks in Java

Shallow Cloning:
public class Test implements Cloneable{
int a=10;
StringBuffer str = new StringBuffer("abc");
public void main (String args[]) throws CloneNotSupportedException{
Test t1 = new Test();
Test t2 = (Test)t1.clone();
t1.a=20;t2.a=30;
t1.str.append("def");t2.str.append("ghi");

System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
System.out.println("t1.str = " + t1.str + " t2.str = " + t2.str);
}
}

Output:
t1.a = 20 t2.a = 30
t1.str = abcdefghi t2.str = abcdefghi

Deep Cloning:

public class Test implements Cloneable{
int a=10;
StringBuffer str = new StringBuffer("abc");
public void main (String args[]) throws CloneNotSupportedException{
Test t1 = new Test();
Test t2 = (Test)t1.clone();
t1.a=20;t2.a=30;
t1.str.append("def");t2.str.append("ghi");
System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
System.out.println("t1.str = " + t1.str + " t2.str = " + t2.str);
}

@Override
protected Object clone() throws CloneNotSupoortedException{
Test t = new Test();
t.str = new StringBuffer();
return t;
}

}
Output:
t1.a = 20 t2.a = 30
t1.str = abcdef t2.str = ghi

(Continued on next question...)

Other Interview Questions