Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic
Author

Garbage Collection

kundana sharma
Greenhorn

Joined: Sep 09, 2012
Posts: 10

At line 20 how many objects are available for Garbage collection?
My Ans is 2 objects will be Garbage Collected.But some say it to be 4.
My Solution:
s1--->SO1. At line 13.Lets acronym Sparrow Object as SO;
s2--->SO2. At line 14.
s3--->SO3. At line 15.
After line 16:s1--->SO3 ,s2--->SO2,s3--->SO3.So SO1 available for GC.
After line 17:s1--->SO3 ,s2--->SO3,s3--->SO3.So SO2 available for GC.
After line 18:s1--->SO3 ,s2--->null,s3--->SO3.
After line 19:As both s1 and s3 refer to same object, nothing much wrt GC is going to happen in this line.
Is this correct? some say 4 objects will be Garbage collected.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37971
    
  22
Please always tell us where such questions come from.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

kundana sharma wrote:
At line 20 how many objects are available for Garbage collection?
My Ans is 2 objects will be Garbage Collected.But some say it to be 4.


It can't be 4, since only 3 objects are ever created.


My Solution:
s1--->SO1. At line 13.Lets acronym Sparrow Object as SO;
s2--->SO2. At line 14.
s3--->SO3. At line 15.


Correct so far

After line 16:s1--->SO3 ,s2--->SO2,s3--->SO3.So SO1 available for GC.

No.
s1-->SO1;s2-->SO2;s3-->SO1. So SO3 eligible for GC.

After line 17:s1--->SO3 ,s2--->SO3,s3--->SO3.So SO2 available for GC.

s1-->SO2;s2-->SO2;s3-->SO1. So still only SO3 eiligible for GC.

After line 18:s1--->SO3 ,s2--->null,s3--->SO3.

s1-->SO2;s2-->nothing;s3-->SO1. So stillonly SO3 eligible for GC.

After line 19:As both s1 and s3 refer to same object, nothing much wrt GC is going to happen in this line.

s1-->SO2;s2-->nothing;s3-->SO2; So now SO1 and SO3 are eligible for GC.

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Garbage Collection
 
Similar Threads
GC question
Garbage Collection and the String Pool
Mock exam question
Garbage Collection and the String Pool
Are string literals garbage collected?