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 of strings ? 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 of strings ?" Watch "Garbage collection of strings ?" New topic

Garbage collection of strings ?

sharon daze

Joined: Feb 08, 2009
Posts: 16
public class ImmutableStrings
public static void main(String[] args)
String one = "someString";
String two = new String("someString");

one = two = null;

How many object are ready to be garbage collection ?
I need explanation in detail.

Sunny Mattas
Ranch Hand

Joined: Apr 22, 2008
Posts: 45

Here two objects will be created at line 1 and 2. Object at 1 will be created at compile time an the string memory pool.And objects present in String memory pool doesnot get garbage collected.

At 2 we are using new keyword so, object will be created only at heap by JVM and "someString" is already there in pool because of line 1 and compiler will not create it again.This will save the memory and is the main use of string memory pool.
So at 3 three object referred by reference variable two is only available for garbage collection.

If I am right garbage collection for strings is not in scope of SCJP.

Sunny Mattas

Sunny Mattas
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
Hi Sharon,

Whenever you're looking at a GC mock question, don't use objects of type String. If the mock question starts discussing the String constant pool, then the question is out of the scope of the real exam.

The real exam has NO GC questions that use objects of type String.



Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
I agree. Here's the link:
subject: Garbage collection of strings ?
It's not a secret anymore!