不知道大家有没有思考过一个这样的问题,Java 中 String 类不是基本数据类型,但是我们在日常使用中,却可以像基本数据类型中一样使用,例如:
int a1 = 1;
String s1 = "s1";
这里就要提到字面量和常量池的概念了,JVM 在方法区中专门有一块常量池区域用来存这些常量。
String.intern()
这个方法很少用,早年间为了应付面试,背过相关的八股文,但是面试完就忘了。最近又是复习为了面试,点进这个方法看了下:
/**
* 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();
该方法详细描述了它的用法和用例,非常贴心,相对比网上的人云亦云,注释上一目了然,现在想想这大概是比以前成熟的表现之一了吧,会先自己看官文,更有耐心找答案,而不是去看别人怎么说的。
用法:当调用这个方法时,如果在 String 常量池中有这个值,那么直接返回,如果没有,那么会添加到 String 常量池中。