intern方法本质上来源于JVM的运行时常量池。具有动态特性,并不一定需要常量编译时才能产生,运行期间也可以把常量放入常量池。
intern 返回的是字符串对象的规范化表示形式,当调用 intern 方法时,如果常量池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。
package test;
public class test {
public static void main(String[] args) {
String a = "12345";
String b = "12345";
System.out.println(a == b);
String c = "basy";
String d = new String("basy").intern();
String d2 = new String("basy");
System.out.println(c == d);
System.out.println(c == d2);
String s1 = "123";
String s2 = new String("123");
System.out.println(s1 == s2);
String s3 = s2.intern();
System.out.println(s1 == s3);
}
}
结果:
true
true
false
false
true
附录:
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();