方法说明
- Returns a canonical representation for the string object.
(返回字符串对象的规范化表示形式) - 参数:无
- 返回值:a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
(与该字符串具有相同内容的字符串,同时保证来自唯一字符串池)
示例(本文示例基于JDK1.8进行测试)
- 先看下面的例子1
public static void main(String[] args) {
String s1 = new String("hello")+new String("Java");
String s3 = "helloJava";
String s2 = s1.intern();
System.out.println("s1: " + System.identityHashCode(s1));
System.out.println("s2: " + System.identityHashCode(s2));
System.out.println("s3: " + System.identityHashCode(s3));
}
-
运行结果:
示例1运行结果 - 结果分析:
s1对应的值"helloJava"被分配在堆上
s3对应的值"helloJava"被分配在常量池中
执行s1.intern()时,系统首先会到常量池中查找是否有字面量是"helloJava"的常量,有则返回对应的引用,本例中由于常量池中已经存在"helloJava"常量,因此返回s3的引用,所以s2和s3地址相同,但与s1不同 -
内存如下:
示例1内存分布
- 再来看示例2
注意:这里将s2和s3定义的顺序颠倒了一下
public static void main(String[] args) {
String s1 = new String("hello")+new String("Java");
String s2 = s1.intern();
String s3 = "helloJava";
System.out.println("s1: " + System.identityHashCode(s1));
System.out.println("s2: " + System.identityHashCode(s2));
System.out.println("s3: " + System.identityHashCode(s3));
}
-
运行结果:
示例2运行结果 - 结果分析:
s1对应的值"helloJava"被分配在堆上
执行s1.intern()时,由于常量池中目前没有"helloJava",因此常量池中新增一块空间用于保存堆中"helloJava"的地址,并将该地址返回给s2,因此s2的指针此时指向的是堆上的"helloJava"。同理,s3从常量池中获取的也是堆上的地址,因此也指向堆。综上:三者的地址相同 -
内存如下:
示例2内存分布