• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection Doubt

 
mamidi venkat
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • 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);
}
 
Anais Aponte
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • 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.
 
Ajay Chandravadiya
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic