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?
The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.
String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.
The intern() method creates an exact copy of a string that is present in the heap memory and stores it in the String constant pool if not already present. If the string is already present, it returns the reference.
Java String intern() method explained with examples This method ensures that all the same strings share the same memory. For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance.
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 theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With