• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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
 
Let's go to the waterfront with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic