Why does the string "I don't get it." get in the string pool.
The "I don't get it." string does not get into the interning pool.
One way to verify it is as follows:
StringBuffer str2 = new StringBuffer(" I don't");
StringBuffer str3 = str2.append(" get it.");
String str = new String(str3.toString());
if (str == str.intern()) {
System.out.println("It was not interned before"); // <<== This is printed
} else {
System.out.println("It was interned before");
}
If String's content is interned, the call of intern() will return a different ("canonical") object. As you can see, the above returns the same object, meaning that the object on which you call intern() just became the "canonical" one (i.e. has been interned).
On the other hand, if you remove the append, you'd get a different result:
StringBuffer str2 = new StringBuffer(" I don't");
StringBuffer str3 = str2;
String str = new String(str3.toString());
if (str == str.intern()) {
System.out.println("It was not interned before"); // <<== This is printed
} else {
System.out.println("It was interned before");
}
Now the string inside str3 is " I don't". Its copy is already interned, because it's the same as the string constant used in creation of the str2.
You can run the first and the second programs side by side to see the difference for yourself.
The reason why str2 == str3 is true has nothing to do with string pools (the slang word is "string interning"). The two are equal because StringBuffer.append returns the object on which the append is invoked, i.e. str2. You do not have a second object - there's only one StringBuffer with two references to it. The content of that StringBuffer is the concatenation of the " I don't" and " get it." strings.
append()returnsthis.inserted into the "String pool"he as implying the StringBuffers value would be interned, that is definitely incorrect.