Java uses a string pool. This is an implementation of the concept of string interning.
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
This means that for every string, a copy of that particular string is added to the string pool. Every variable that holds that exact string, points to that copy in the string pool.
The strings Hello.
,
, and My name is Kevin
are added to the string pool, since they're literals in the program.
String myString = "Hello.";
The variable myString
starts pointing to the string Hello.
, which is already in the string pool.
myString += " ";
The string Hello.
(note the extra space at the end) is added to the pool. The variable myString
now points to that.
myString += "My name is Kevin";
The string Hello. My name is Kevin
is added to the pool. The variable myString
now points to that.
Strings in the pool that are no longer being referenced by variables, are eligible for garbage collection, so Hello.
(with the space at the end), can now be garbage collected.