Valhalla Legends Forums Archive | Java Programming | garbage collection

AuthorMessageTime
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'.

[code]
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
}

[/code]


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 ?
March 10, 2004, 8:26 AM
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)
March 10, 2004, 2:22 PM
touchstone
hmm...i also think so . probabily the answer in the site is wrong.
March 10, 2004, 2:41 PM
Nova1313
[quote author=touchstone link=board=34;threadid=5708;start=0#msg48721 date=1078929677]
hmm...i also think so . probabily the answer in the site is wrong.

[/quote]

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.
March 11, 2004, 4:30 PM
iago
[quote author=Nova1313 link=board=34;threadid=5708;start=0#msg48915 date=1079022611]
[quote author=touchstone link=board=34;threadid=5708;start=0#msg48721 date=1078929677]
hmm...i also think so . probabily the answer in the site is wrong.

[/quote]

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.
[/quote]

How would you access "1" if there aren't any variables pointing to it?
March 11, 2004, 4:43 PM
touchstone
[code]
"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

[/code]

hmm...its difficult to grasp. note "0" is there.
March 12, 2004, 5:57 PM
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
March 13, 2004, 5:12 AM

Search