File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection Doubt" Watch "Garbage Collection Doubt" New topic

Garbage Collection Doubt

mamidi venkat
Ranch Hand

Joined: Jul 03, 2007
Posts: 63
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;
Anais Aponte

Joined: Jul 24, 2007
Posts: 8
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.

Anais Aponte
Ajay Chandravadiya

Joined: Aug 06, 2007
Posts: 27
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.

SCJP Tiger Hunter 91%.
I agree. Here's the link:
subject: Garbage Collection Doubt
jQuery in Action, 3rd edition