• 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Garbage Collection Doubt

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all

Here i have doubt how many objects are eligible for the garbage collection
and one more thing is line 5 is eligible for the GC. What happen for the line 6???


1. String a,b;
2. a=new String("hello world");
3. b=new String("game over");
4. System.out.println(a+b+"ok");
5. a=null;
6. a=b;
System.out.println(a);
}
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, mamidi

In this piece of code, you have only one object eligible for the garbage collection and is the object String "hello world". In the line 5 is justly where the object String "hello world" is eligible for GC because the reference 'a' leave to reference. And in the line 6 both the reference 'a' and the reference 'b' are aiming at the same object "game over". Don't forget that the reference and the object are things different and lives in memory distinct. The reference live in the stack and de object lives in the heap. I hope help you.
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
nope.
When you said System.out.println(a+b+"Ok") , it created 2 new String objects:
1."ok" 2. the combination of a+b+ok

so total 3 objects, these two and a, are eligible for GC.
 
Always! Wait. Never. Shut up. Look at this tiny ad.
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic