jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage collect with String Objects 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 collect with String Objects" Watch "Garbage collect with String Objects" New topic

Garbage collect with String Objects

P Malhotra

Joined: Jul 27, 2011
Posts: 7

Hello everyone

I am using string and I know that we can create string objects by two different ways:

1) String s="Hello"; //Line1
2) String s1= new String("Hello"); //Line2

so if we are using the code written in Line1 that means we are creating a String object in the String literal pool
the Line2 will create an String object in Heap

So what is String literal pool ?
Is it like heap or it is a table where we can store actual objects reference.


when will garbage collect remove the String objects from the heap


Naveen Madarapu
Ranch Hand

Joined: May 24, 2011
Posts: 64

Remember objects are always created on heap only. //created in line1 and line2
String pool is an constant memory location which is store the literal objects reference.

P Malhotra

Joined: Jul 27, 2011
Posts: 7

Thanks for your reply

and what about the garbage collect if pool is holding the address of the object than when will garbage collect remove the Objects.
Prabhjot Jassal

Joined: Jul 19, 2010
Posts: 22
You have 2 objects on the heap (i am not too sure about the string pool ..so there might be only 1 object in heap)

The objects are eligible to remove from the memory when they are no longer referenced. Eg. if i say s = null, then there will be no way to get "Hello" object on the heap (assuming there are 2 objects on the heap)

Could please someone clarify how many objects would be in the heap? Thanks
Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

Core Java please check your private messages for some administrative matter...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
On the real exam GC questions NEVER 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: http://aspose.com/file-tools
subject: Garbage collect with String Objects
It's not a secret anymore!