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 if s.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.来源:String.intern
大意是,当常量池包含一个字符串equals当前这个字符串,则返回常量池里的字符串,否则将当前字符串添加到常量池,并且返回一个当前字符串的引用。
我们先看下面的例子:
String s= "abc"; String sa=new String("abc"); String sb=new String("abc"); System.out.println( s == sa ); // false,s指向常量池中的"abc",sa指向堆中的新的"abc" sa.intern(); sb=sb.intern(); // 由于常量池中存在abc,因此把常量池中“abc”的引用赋给sb System.out.println( s==sa);//false System.out.println( s==sa.intern() );//true System.out.println( s==sb );//true 为了验证当常量池中没有值为abc的字符串时intern的行为,可以参考下面的例子: String sa=new String("ab") + "c"; String sb=sa.intern(); System.out.println( sa == sa.intern() ); System.out.println(sa); System.out.println(sb); System.out.println(sb == sa.intern());结果为: true abc abc true 由此我们可以见到,上例中sa实际就是常量池中的值为“abc”的字符串。只得注意的是,当上例第一行代码改一下,结果就会不同
String sa=new String("abc"); String sb=sa.intern(); System.out.println( sa == sa.intern() ); System.out.println(sa); System.out.println(sb); System.out.println(sb == sa.intern());结果为 false abc abc true原因是 String sa=new String("abc"); 这句实际上已经在常量池中创建了一个值为”abc“的常量。若想了解其中更多的细节,建议大家看看这篇文章【总结】String in Java