• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection of strings ?

 
sharon daze
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
 
Sunny Mattas
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
SCJP5
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

hth,

Bert
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic