Sunday, June 18, 2006

Are string literals garbage collected?

The answer is no. String class maintain a list of references to string(in heap) in the constant pool. When new is used to create string, then a new string object is created in heap and the reference to this object is returned to the code. Thus, we will have two string objects. If intern() method is called on this object, then the reference to the other string object(whose reference is maintained in literal pool) is returned to the code and the string object created using new will be garbage collected. Even when there are no references to the string literal object, string literal will not be garbage collected, because the reference to this object is still maintained in the string literal pool

No comments: