Quote:
|
Originally Posted by pjerald what is the use of String.intern(). Is there any difference between a copy of a string object and the return value of this function ?
This function also returns a copy of the string which it acts on. Clear me please. |
When you use literal Strings in your program (and most likely you do), the javac
compiler collects those strings. When you want to run your program those literal
Strings are stored in a String pool. It stores just unique Strings in that pool, so:
-
String s1= "foo";
-
String s2= "foo";
-
This takes up one String in that pool: "foo" and both pointers s1 and s2 point to
that single String. You can put Strings in that pool too by using the String.intern()
method:
-
String s1= new String("foo");
-
String s1= new String("foo");
-
s1= s1.intern();
-
s2= s2.intern();
-
After the initialization s1 and s2 point to two different String instances, both
having the value "foo". The literal String "foo" used for the instantiation of the
Strings is stored in the String pool. After the initialization there are *three* strings
"foo".
After interning both Strings in the last two statements there's still one String "foo"
in the String pool (because it already was there) and both references s1 and s2
point to it. The two other String instantiations (that also contained "foo" but not
the same as the one in the pool) can be garbage collected because nothing points
to them anymore.
When cleverly used that pool can save you quite a bit of memory.
kind regards,
Jos