Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Variables out of scope eligible for garbage collection

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
------------------
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Manfred, you are right. This has been discussed a lot.
thanks,
carlo
 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also the loops runs until the i==0;
If you manually count it, it would make 11
 
A day job? In an office? My worst nightmare! Comfort me tiny ad!
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic