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 String 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 "String" Watch "String" New topic


m wasimullah

Joined: Mar 01, 2007
Posts: 4
String s="abc";
In the above code, the object representing "abc" will become eligible for garbage collection or will stay in string pool.

Thanks in advance.
sadasiva kumar
Ranch Hand

Joined: Oct 30, 2003
Posts: 91
A local variable lives only within the method that declared the variable.
An instance variable lives as long as the object does.If the object is still alive,so are its instance variables.

Here the variable 's' is in scope only within its method.So 's' becomes eligible for garbage collection.

A bend in the road is not the end of the road ... unless you fail to make the turn.
deepak adlakha
Ranch Hand

Joined: Jul 27, 2001
Posts: 325
"s" wont be eligible for garbage collection as its still pointing to new object which is created. "abc" will be eligible for GC, if we dont have any more reference in string pool referening to this.
megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
GC runs only on the objects on the heap to make memory available as needed.
"abc" is created in the string constact pool.GC does not run there.
So "abc" will not be garbage collected.

As a side note garbage collection with strings is not in the exam.
ZHU Yinli

Joined: Mar 20, 2007
Posts: 1
Can we say that the objets which are created by new is in the pool, the others will be collected?
Kevin Liu

Joined: Mar 17, 2007
Posts: 10
Originally posted by megha joshi:

So "abc" will not be garbage collected.

I agree. Here's the link:
subject: String
It's not a secret anymore!