Steve P.
Steve P.

Reputation: 14699

Memory allocation/management for strings and their subsequent garbage collection

String a = "test";
String b = "whatever";
String c= "test";

System.out.println(a == c); //true

I assume that this prints true because strings are immutable and therefore these strings are identical, so Java will point c to a's location in memory.

String a = "test";
String b = "whatever";
String c= new String("test");

System.out.println(a == c); //false

I assume that by invoking the new operator, Java must allocate new memory, so it can't choose to point to a.

My question is:

String d="a";
d="rbf";
d="ergfbrhfb";
d="erhfb3ewdbr";
d="rgfb";
//...

Upvotes: 0

Views: 233

Answers (2)

Tim Bender
Tim Bender

Reputation: 20442

What's going on with respect to the memory allocation of the intermediary assignments to d?

Since the assignments are all to String literals, those literals are compiled into the class. Basically, literal strings of characters are handled a little differently than dynamic ones (like user input).

Does this answer change if subsequent assignments are of the same number of characters? (ie, d="abc"; d="rfb";)

No. The String literals are all interned as separate objects when the class is loaded. Even if the assignment were from user input, the answer is still no. Instances of String are immutable. Meaning that the encapsulated representation of a String is not allowed to change. So, if a String were for instance a char[], no operation would ever be allowed to change the elements of that char[].

Is new memory being allocated for each change to d?

No, again, because the assignments are to String literals and not to new instances of a String or arbitrary input data.

If so, when does the memory allocated for each assignment become free again?

Theoretically, if the Class were to be "unloaded" by destroying the ClassLoader then perhaps the interned literals could be GCed.

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

In your last example there is no memory allocation or freeing memory, String constants stay permanently in memory in a String pool, variable d will be just assigned different references to those Strings.

Upvotes: 3

Related Questions