• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

doubt in garbage collection

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe it's array s0 and 2 String object with 3,4.
 
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 9031
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to all of you
 
reply
    Bookmark Topic Watch Topic
  • New Topic