File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in garbage collection" Watch "doubt in garbage collection" New topic

doubt in garbage collection

shruthi sridhar

Joined: Oct 10, 2007
Posts: 11
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

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];
return s1;

Ans: 3
But i think its 2...
How is it 3???
P Ventura
Ranch Hand

Joined: Jan 24, 2007
Posts: 42
Maybe it's array s0 and 2 String object with 3,4.

Objective: SCJP 1.5<br /><a href="" target="_blank" rel="nofollow">API</a><br /> <blockquote><font size="1" face="Verdana, Arial">code:</font><hr><pre><font size="2"><br />Double n1 = Double.NaN; Double n2 = Double.NaN;<br /> n1.equals(n2) // true even though Double.NaN != Double.NaN<br />-0.0 == +0.0; // true<br />Double n1 = -0.0;Double n2 = +0.0;<br />n1.equals(n2) // false even though -0.0 == +0.0<br /></font></pre><hr></blockquote>
Doug Slattery
Ranch Hand

Joined: Sep 15, 2007
Posts: 294
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.

-- Nothing is impossible if I'mPossible
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
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.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
shruthi sridhar

Joined: Oct 10, 2007
Posts: 11
Thanks to all of you
I agree. Here's the link:
subject: doubt in garbage collection
It's not a secret anymore!