• 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

when the object will be garbage collected?

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
friends,

when the String object created in for loop will

be first eligible for garbage collection?

1. public void countDown(){
2. for(int i=10 ; i>=0 ; i--){
3. String temp=Integer.toString(i);
4. }
5. }

options:
A)after program exit the for loop
B)after program exit the method
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is a very interesting question. It seems to depend on how smart the compiler and runtime are. In Java 1 objects like that were not collected until the method exited, but some experiments (with objects that have a finalize method) have shown that present Java will collect them when out of scope.
The behaviour is not defined in the JLS as far as I know.
Bill
 
yashendrakar chandrakar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
William,
Let's take simple one.actually i just want to know in general.
1. public void aMethod(){
2. if(true){
3. String temp=new String("StrOb");
4. }
5. }

here the object created in line 3 will be first eligible for garbage collection ,after line 4 or 5 (ie.after exiting if block or after exiting aMethod?
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the previous answer was accurate.
Besides try this code. It shows that for my compiler the local variables need to be set to null to be recycled:
 
Live a little! The night is young! And we have umbrellas in our drinks! This umbrella has a tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic