0
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";
//...
  • What's going on with respect to the memory allocation of the intermediary assignments to d?
  • Does this answer change if subsequent assignments are of the same number of characters? (ie, d="abc"; d="rfb";)
  • Is new memory being allocated for each change to d?
  • If so, when does the memory allocated for each assignment become free again?
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Steve P.
  • 14,489
  • 8
  • 42
  • 72

2 Answers2

3

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

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.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • I didn't know interned `String`s could be GC'd when the class that created them was unloaded - do you a reference in the JLS for that? – Boris the Spider May 24 '13 at 08:01
  • I used lots of soft words like "theoretically" and "perhaps". I'm not positive. Found this: http://stackoverflow.com/a/15324431/122207 – Tim Bender May 24 '13 at 08:17
  • And this: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html – Tim Bender May 24 '13 at 08:21