Valhalla Legends Archive

Programming => General Programming => Java Programming => Topic started by: touchstone on March 10, 2004, 02:26 AM

Title: garbage collection
Post by: touchstone on March 10, 2004, 02:26 AM
hi, i was trying to solve this question

enter the number of  String objects eligible for garbage collection at 'line y' which were created at 'line x'.


public void countDown(){
   String s = null;
   for (int i=3; i>=0; i--){
   s = String.valueOf(i);    //line x
   }
   System.out.println("Done");    //line y
}




Answer : 2

i could not make out this answer.

in fact, i see for loop will  run  for   i=3, i=2, i=1 and i=0 and cosequently s will be updated four times with the value i ( but as a string)

then the loop will be finished  and print satement will come.

how the answer is 2 ?

garbage collection means the objects are no longer usued.  which way   the answer is 2 ?
Title: Re:garbage collection
Post by: iago on March 10, 2004, 08:22 AM
I would say the answer is 3, it *could* garbage collect "3", "2", and "1" (not that it will, but they are eligible for it)
Title: Re:garbage collection
Post by: touchstone on March 10, 2004, 08:41 AM
hmm...i also think so .  probabily the answer  in the site is wrong.
Title: Re:garbage collection
Post by: Nova1313 on March 11, 2004, 10:30 AM
Quote from: touchstone on March 10, 2004, 08:41 AM
hmm...i also think so .  probabily the answer  in the site is wrong.


it's 2. Java is going to make a new string every time it loops. So it will clean up 2. The first one "3" and the second "2".

"1" will not be cleaned up until the function exits because it's still in it's lifetime. So at the point it says done "1" is still availiable to be accessed.
Title: Re:garbage collection
Post by: iago on March 11, 2004, 10:43 AM
Quote from: Nova1313 on March 11, 2004, 10:30 AM
Quote from: touchstone on March 10, 2004, 08:41 AM
hmm...i also think so .  probabily the answer  in the site is wrong.


it's 2. Java is going to make a new string every time it loops. So it will clean up 2. The first one "3" and the second "2".

"1" will not be cleaned up until the function exits because it's still in it's lifetime. So at the point it says done "1" is still availiable to be accessed.

How would you access "1" if there aren't any variables pointing to it?
Title: Re:garbage collection
Post by: touchstone on March 12, 2004, 11:57 AM

"1" will not be cleaned up until the function exits because it's still in it's lifetime. So at the point it says done "1" is still availiable to be accessed



hmm...its difficult to grasp. note  "0" is there.
Title: Re:garbage collection
Post by: Nova1313 on March 12, 2004, 11:12 PM
my mistake i did not see the >= i just thougth it was >.. IT's 3 then.. 3,2,1 and the last one would be zero...

the page is wrong. Sorry