一.intern方法
1.定义
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class <code>String</code>.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this <code>String</code> object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this <code>String</code> object is added to the
* pool and a reference to this <code>String</code> object is returned.
* <p>
* It follows that for any two strings <code>s</code> and <code>t</code>,
* <code>s.intern() == t.intern()</code> is <code>true</code>
* if and only if <code>s.equals(t)</code> is <code>true</code>.
* <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();
根据源码的解释,该方法返回常量池中对应的字符串,若常量池中存在该字符串,直接返回该对象引用,若不存在,将该字符串对象加入常量池然后再返回其引用。
注意: 字符串常量在jdk1.7之前存在方法区,jdk1.7之后移到了堆中。
2.应用
见博客https://www.cnblogs.com/Kidezyq/p/8040338.html
二.String中面试涉及到的问题
1.JDK 6和JDK 7中substring的原理及区别
https://blog.csdn.net/renfufei/article/details/14058047