After line 6, how many objects are eligible for garbage collection?
The answer is "2" which I'm unable to comprehend...!!!
This is what I know:
1. C1 is given a reference to a newly created C's object on the heap (let's call it Obj_c1) 2. When m1(C1) is called, a copy of the reference to the same object above is passed, i.e., the reference of Obj_c1 is passed. We now have the copy of the reference in variable ob1 - local variable of the method! 3. Now, ob1 is given a new object's reference, let's call the object on the heap, Obj_ob1. Here, the reference to Obj_ob1 is returned to variable c1. 4. In the previous step, since the ref to Obj_c1 is copied into the local method variable, and this local variable is changed, there is no change to variable c1, which still holds the reference to Obj_c1. 5. After the method execution we now have, c1 -> Obj_c1 and c2->Obj_ob1 6. Now, c3 is given a new reference to the heap object Obj_c3 7. Line # 6 would create c2 to get the reference of c3, which is c2->Obj_c3 8. Finally there are three objects on the heap, Obj_c1, Obj_ob1 and Obj_c3 9. The only dangling object without a reference variable is Obj_ob1, as line 6 removes the reference and re-refers variable c2 to Obj_c3 10. So this makes only one object GC elligible!
Am I right with those steps above or is there a point where I made a BIG blunder!!!
Thanks in advance, Lakuma
[ September 29, 2008: Message edited by: Lakuma Yalamanchili ]
[ September 29, 2008: Message edited by: Lakuma Yalamanchili ] [ September 29, 2008: Message edited by: Lakuma Yalamanchili ]
4. In the previous step, since the ref to Obj_c1 is copied into the local method variable, and this local variable is changed, there is no change to variable c1, which still holds the reference to Obj_c1.
As per my understanding the answer is 2. The refernce c1 is passed to the method, and inside the method this reference has been assigned a new object. So, the object created in the previous step is eligible for garbage colletion. (Don't get confused with reference being assigned to a local variable inside the method. The variable still holds refence to the object created in previous step.)
someone correct me if i'm wrong
-Aravind<br />SCJP 5.0 (91%), Preparing for SCBCD.
posted 11 years ago
I'm sorry, I wasn't aware that we had to quote our source. Thanks for mentioning it Henry.
According to me ob1(local var) is still referencing the obj- ob1. Since, it is created inside the method there is no reference? Please correct me.
Thank You Saritha
posted 11 years ago
Thanks for your update, I feel better..!!
The local variable ob1 does refer to obj_ob1, but once the execution call is out of the method "m1", the local variable does not exist as the scope of it lies within the method. But the reference that it created is passed onto c2. So after the method execution: