Reputation: 1
String s1 = new String("1") + new String("1");
s1.intern();
String s2 = "11";
System.out.println(s1 == s2);//jdk6:false;jdk7:true;jdk8:true;jdk17:false
The same code above is false in jdk6, but true in jdk7 and jdk8, and false in jdk17. Why is this?
I want to know what changes have occurred here
Upvotes: 0
Views: 92
Reputation: 21630
String.intern()
behaves as specified.
From the JavaDoc of Java 1.0.2
Creates a canonical representation for the string object.
If s and t are strings such that s.equals(t), it is guaranteed that s.intern() == t.intern()
Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
to the JavaDoc of Java 22:
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
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.
It follows that for any two strings s and t,
s.intern() == t.intern()
is true if and only ifs.equals(t)
is true.All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java Language Specification.
Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
it never guarantees that for a randomly constructed string s1 == s1.intern()
will return true.
Especially in some Java versions (probably starting from 1.1 up to Java 1.6) the interned strings are maintained in a special memory segment called the PermGen space. Randomly generated strings are stored in the normal heap, and calling String.intern()
on a string that is stored in the heap will return another string (containing the same sequence of characters) that resides in the PermGen space. This is handled in the symbolTable.cpp source file
Upvotes: 1