Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in garbage collection

 
shruthi sridhar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How many objects are eligible for garbage collection after line1?


public class Test{
public static void main(String args[]){
Test test=new Test();
String[] s=test.f() //line 1
System.gc();
Thread.sleep(2000);
}

public String[] f(){
String[] s = new String[4];
for(int i=0;i<s,length;i++)
s[i]=new String(""+i);
String[] s1=new String[2];
s1[0]=s[0];
s1[1]=s[1];
return s1;
}
}

Ans: 3
But i think its 2...
How is it 3???
 
P Ventura
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe it's array s0 and 2 String object with 3,4.
 
Doug Slattery
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that local variables are stored on the stack and GC doesn't apply to them. Local variables dissolve automatically when the method ends.

In this case, a new string object s1 is created in method f(). s1[0] gets assigned s[0], so another string object is created, but in the array. The same applies to s1[1]. When f() returns s1, there are 3 object: the s1 array and the two array elements assigned with String objects.

Hope this helps.
Aloha,
Doug

-- Nothing is impossible if I'mPossible
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For anyone keeping score, remember that on the real exam GC questions will never use objects of type String. To keep things simple, whenever you see a mock GC question that uses objects of type String, substitute objects of another type. And if you see the answer for a mock exam discuss the String constant pool - relax - that's way outside the scope of the real exam.
 
shruthi sridhar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all of you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic