When you use intern()
on string that wasn't in string pool earlier this string will be placed there and every next literal will use reference to it.
But if there is already some literal in strings pool and you will try to invoke intern()
on newly created string object with same characters, it will not be placed in pool but will only return reference to string from pool. Also it will not change reference to original string on which intern
was invoked.
Since Java loads and executes some code before executing main
method there is a chance that some literals will be placed in string pool before execution of main
code.
For example String pool will contain literals such as "UTF-8"
, "charset"
, "charsetName"
, which may come from java.lang.String
, or java.nio.charset.Charset
classes. It seems that "string"
literal is one of them (I am not sure where exactly it was added to String pool).
So when you are invoking
String str11="str";
String str12="ing";
String concat11=str11+str12;
concat11.intern();
your intern
will not put "string"
from concat11
in string pool because there is one already there and other "string"
literals (like these you used in =="string"
part) will be using the one from string pool, not from concat11
.
Lets test this theory:
String s = "ABCdef";// this string will be placed in
// string pool before rest of code
String str1 = "ABC";
String str2 = "def";
String concat1 = str1 + str2;
concat1.intern();//this will only return reference to literal from pool
System.out.println(concat1 == "ABCdef");//false
// here we don't have any "ABcd" literal in pool yet
String strA = "AB";
String strB = "cd";
String concatAB = strA + strB;
concatAB.intern();//so this will put String object from concatAB to pool
System.out.println(concatAB == "ABcd");//and "ABcd" literal will use same object
output
false
true