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.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variables out of scope eligible for garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Variables out of scope eligible for garbage collection" Watch "Variables out of scope eligible for garbage collection" New topic
Author

Variables out of scope eligible for garbage collection

Carlo Smits
Greenhorn

Joined: Jul 09, 2001
Posts: 22
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
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
Hi Manfred, you are right. This has been discussed a lot.
thanks,
carlo
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Also the loops runs until the i==0;
If you manually count it, it would make 11
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Variables out of scope eligible for garbage collection
 
Similar Threads
How many reference are left?
Garbage collection question from J@Whiz1.4
Garbage Collection
gc
Local variable and Garbage Collection