ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java `String intern()`方法 > 原文: [https://beginnersbook.com/2017/10/java-string-intern-method/](https://beginnersbook.com/2017/10/java-string-intern-method/) Java `String intern()`方法用于从内存中获取字符串(如果已存在)。此方法可确保所有**相同的字符串**共享相同的内存。例如,使用`intern()`方法创建一个字符串`"hello"` 10 次将确保内存中只有一个`"Hello"`实例,并且所有 10 个引用都指向同一个实例。 ## 一个简单的 Java `String intern()`方法示例 此示例演示了`intern()`方法的用法。此方法在内存池中搜索提到的`String`,如果找到该字符串,则返回它的引用,否则它为该字符串分配新的内存空间并为其分配引用。 ```java public class Example{ public static void main(String args[]){ String str1 = "beginnersbook"; /* The Java String intern() method searches the string "beginnersbook" * in the memory pool and returns the reference of it. */ String str2 = new String("beginnersbook").intern(); //prints true System.out.println("str1==str2: "+(str1==str2)); } } ``` 输出: ```java str1==str2: true ``` ## Java 字符串字面值 当我们使用字符串字面值创建字符串而不是使用`new`关键字创建字符串时,java 会自动实例化字符串。让我们举个例子来理解这个: ```java public class Example{ public static void main(String args[]){ String str1 = "Hello"; //Java automatically interns this String str2 = "Hello"; //This is same as creating string using string literal String str3 = "Hello".intern(); //This will create a new instance of "Hello" in memory String str4 = new String("Hello"); if ( str1 == str2 ){ System.out.println("String str1 and str2 are same"); } if ( str2 == str3 ){ System.out.println("String str2 and str3 are same" ); } if ( str1 == str4 ){ //This will not be printed as the condition is not true System.out.println("String str1 and str4 are same" ); } if ( str3 == str5 ){ System.out.println("String str3 and str5 are same" ); } } } ``` 输出: ```java String str1 and str2 are same String str2 and str3 are same String str3 and str5 are same ``` #### 相关文章: 1. [Java `String format()`方法](https://beginnersbook.com/2017/10/java-string-format-method/) 2. [Java `String matches()`方法](https://beginnersbook.com/2013/12/java-string-matches-method-example/) 3. [Java `String trim()`和 hashCode()方法](https://beginnersbook.com/2013/12/java-string-trim-and-hashcode-methods/) 4. [Java `String replace()`,`replaceFirst()`和`replaceAll()`方法](https://beginnersbook.com/2013/12/java-string-replace-replacefirst-replaceall-method-examples/) #### 参考: * [`intern()`方法 - JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()) * [什么是`String` interning?](https://stackoverflow.com/questions/10578984/what-is-string-interning) * [Java 中的`intern()`方法的目的](https://stackoverflow.com/questions/22473154/what-is-the-purpose-of-javas-string-intern)