public static void main(String[] args) {
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);
String str2 = new StringBuffer("ja").append("va").toString();
System.out.println(str2.intern() == str2);
}
Results:
true
false
First one prints true
, and the second prints false
. Why are the results different?
Because your assignments don't re-read from the intern pool and Java
String
(s) are immutable. ConsiderThe output is (as you might expect)
Lots of answer before mentioned about the pool and explained really clearly with the Oracle link docs.
I just would like to point out the way we can check when debugging code.
You can use any IDE and debug to check the actual address that the str1 and str1.intern()/str2 and str2.intern().
let me add something more interesting:
so I think the right answer is :
diffrent vendor's jvm or jvm versions may have diffrent implemention(the language specification don't force the how to)
In Oracle JDK 8(I guess u using): String “java” already in pool(loaded by java.lang.Version#laucher_name) and String pool only stores the refrence,not the object.
But in OpenJDK the laucher_name is "openJDK";In Oracle JDK 6 and below ,the string pool will copy the string object to itslef.
The difference in behavior is unrelated to the differences between
StringBuilder
andStringBuffer
.The javadoc of
String#intern()
states that it returnsThe
String
created fromis a brand new
String
that does not belong to the pool.For
to return
false
, theintern()
call must have returned a different reference value, ie. theString
"java"
was already in the pool.In the first comparison, the
String
"计算机软件" was not in the string pool prior to the call tointern()
.intern()
therefore returned the same reference as the one stored instr2
. The reference equalitystr2 == str2
therefore returnstrue
.