aspose file tools
The moose likes Java in General and the fly likes Strings, Immutablilty, and Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Strings, Immutablilty, and Garbage Collection" Watch "Strings, Immutablilty, and Garbage Collection" New topic
Author

Strings, Immutablilty, and Garbage Collection

Peter Kleczka
Greenhorn

Joined: Feb 09, 2003
Posts: 18
Hi

I'm working with code that changes the color of alternating
table rows on a JSP. The following code is in a loop:

String colorString = ""
if (count%2 == 0)
{
colorString = SomeClass.A_STATIC_CONSTANT_1;
} else {
colorString = SomeClass.A_STATIC_CONSTANT_2;
}

Even though colorString is pointing to a constant, is
this not creating a new string for garbage collection
in each iteration of the loop?

Thanks,
Peter (pkleczka@yahoo.com)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

No. Take a few minutes and read this and this; you'll be glad you did, and you'll definitely understand my answer.


[Jess in Action][AskingGoodQuestions]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
as Ernest says: it is just referring to the Object instance...
Peter Kleczka
Greenhorn

Joined: Feb 09, 2003
Posts: 18
Thanks Ernest

This makes sense now. Since the static references are going to hang around "forever" there is nothing to be garbage collected. But I assume the
original assignment (String colorString = "") would leave the empty string in garbage collection territory since there is nothing to reference it.

Thanks again,
Peter
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Actually no, since it is a 'String Literal' it will be interned and also hang around forever. There will be only one instance of String that contains "" unless one is created as new String("");
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings, Immutablilty, and Garbage Collection
 
Similar Threads
the "+" operator
How many reference are left?
doubt on garbage collection
Color object
Garbage Collection of Objects in a for loop