The difference in behavior is unrelated to the differences between StringBuilder
and StringBuffer
.
The javadoc of String#intern()
states that it returns
When the intern method is invoked, if the pool already contains a
string equal to this String
object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this
String
object is added to the pool and a reference to this String
object is returned.
The String
created from
String str2 = new StringBuffer("ja").append("va").toString();
is a brand new String
that does not belong to the pool.
For
str2.intern() == str2
to return false
, the intern()
call must have returned a different reference value, ie. the String
"java"
was already in the pool.
In the first comparison, the String
"计算机软件" was not in the string pool prior to the call to intern()
. intern()
therefore returned the same reference as the one stored in str2
. The reference equality str2 == str2
therefore returns true
.
t understand what
s your point? – Atworthtrue
, or why they should both return the same result. – Mcgaha