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 question 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 question" Watch "garbage collection question" New topic

garbage collection question

sarim raza
Ranch Hand

Joined: Nov 02, 2000
Posts: 232
How many objects are eligible for garbage collection once execution has reached the line labeled Line A?
String name;
String newName = "Nick";
newName = "Jason";
name = "Frieda";
String newestName = name;
name = null;
//Line A
Sateesh Kumar

Joined: Nov 02, 2000
Posts: 2

Hai ,

1) Initially name is pointing to null.
2) newName is pointing to "Nick" ,( Object creted in String Pool)
3) newName is pointing to "Jason" , ( -do-)
so nothing is pointing(referring) to "NICK"
4) now name is pointing to "Frieda" (-do-)
5) newestName is also poining to "Frieda"
6) name is null ,but newestName is pointing to "Frieda"
7) So , only "NICK" can be gc'ed.
Shan Karawita
Ranch Hand

Joined: Oct 13, 2000
Posts: 83
Thank You very much for your clear explanation. I also had a doubt about this kind of questions.Thank a lot for helping me to clear my problem.

Subramaniam Chidambaram

Joined: Oct 18, 2000
Posts: 7

In the above piece of code the String literal "Nick" would not be garbage collected since this would go to the String pool.
Can somebody throw some light on Garbage collection with respect to String pools ?

nutan prakash

Joined: Oct 28, 2000
Posts: 16
The JVM Maintains a String Pool... for example...
1: String s1="Hello";
2: String s2="Hello";
3: String s3=new String("Hello");

In Line 1, the JVM creates a String "Hello" (LITERAL), and passes the reference to s1. In Line 2, the JVM sees that another string "Hello" has to be created, instead of creating one, it passes the reference of the previously created String to s2. FOR EFFICIENCY. That's why (s1==s2) is true.
The JVM maintains this pool.. consisting of strings created from only LITERALS. Hope you got the point. So you can see that (s2==s3) returns false.
ANYBODY: is this correct?

P.Nutan Prakash<br />SCJP2
parag bharambe
Ranch Hand

Joined: Sep 01, 2000
Posts: 41
You are right nutan. JVM maintain string pool of literals.
In above example all are literals and no objects.
As objectes are created with new operator, which is not done here.
So will these literals will be garbage collected
Pleaethrow some light on which one will be garbage collected
Subramaniam Chidambaram

Joined: Oct 18, 2000
Posts: 7
I think the String literals in the string pool will not be garbage collected.
But m doubt is will it be garbage collected only when the JVM is restarted ?
I agree. Here's the link:
subject: garbage collection question
jQuery in Action, 3rd edition