This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Variables out of scope eligible for garbage collection
Carlo Smits
Greenhorn
Joined: Jul 09, 2001
Posts: 22
posted
0
In J@whiz I found the following question When the program reaches line 8, how many of the String objects created in line 3 are eligible for garbage collection? 1.public void countDown() 2.{ 3. for( int i = 10 ; i >= 0 ; i-- ) 4.{ 5.String tmp = Integer.toString( i ); 6.System.out.println( tmp ); 7. } 8.System.out.println("BOOM!"); 9.} The answer is 10 (not 11) because even though the tmp variable is out of scope in line 8, the local variable still has a reference. When does the 11th variable become eligible for GC? Is it when the method ends? ------------------
Manfred Leonhardt
Ranch Hand
Joined: Jan 09, 2001
Posts: 1492
posted
0
Hi Carlo, I think 11 is the correct answer. Any time a variable goes out-of-scope it doesn't exist anymore hence no references to it exist. Therefore, it is elegible for garbage collection! If you don't believe my then try using the last string object being referenced by tmp. The compiler won't let you ... I seem to remember a while ago someone in one of these forums has already refuted the 10 as a result in favor of 11. Regards, Manfred.
Carlo Smits
Greenhorn
Joined: Jul 09, 2001
Posts: 22
posted
0
Hi Manfred, you are right. This has been discussed a lot. thanks, carlo
Ragu Sivaraman
Ranch Hand
Joined: Jul 20, 2001
Posts: 464
posted
0
Also the loops runs until the i==0; If you manually count it, it would make 11