• Welcome to Valhalla Legends Archive.
 

garbage collection

Started by touchstone, March 10, 2004, 02:26 AM

Previous topic - Next topic

touchstone

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 ?

iago

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)
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


touchstone

hmm...i also think so .  probabily the answer  in the site is wrong.

Nova1313

#3
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.

iago

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?
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


touchstone


"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.

Nova1313

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