hello sri,
i ahve an example for you.
public class emp{ //line 1
public static void main(
String[]s){ //line 2
emp e1,e2,e3,e4,e5; //line 3
e1=new emp(); //line 4
e2=new emp(21,"xyz"); //line 5
e3=e2; //line 6
e1=e3; //line 7
e3=new emp(); //line 8
e2=e3; //line 9
e4=e1; //line 10
e1=e2; //line 11
e5=e2; //line 12
}}
here object created at line 4 is garbage collected.
-------------------explanation----------------------------
1)at line 4 and 5 two different objects are created and there references are given by e1 amd e2.
2)in line 6, e3 is reffering same object that was reffered by e2.
3) at line 7 e2 is reffering the object which is initially reffered by e1.now note the object which was initially reffered by e2 is now only reffered by e3 not by e2.
4)in line 8 e1 is reffering the object which is reffered by e3 also.note the object which was initially reffered by e1 is now reffered only by e2 due to line 7.
5)at line 9 a new object is created and is reffered by e3.note the object which was earlier reffered by e3 is now only reffered by e1.
6)at line 10 e2 is reffering the same object which is reffered by e3 at line 9.
please note here that the object created at line 4 has no reference because the latest reference e2 is now reffering another object. hence the object that created at line 4is garbage collected.
for rest of the lines i am not giving explanations.
if you have any doubt please fill free to write me.
thanks
gautam