定义
首先看下String的Intern方法的API定义
/**
* 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();
简单翻译过来就是:
当intern方法被调用时,如果字符串池里已经包含一个相同的字符串对象(使用equals方法判定),那么将返回字符串池中的那个字符串对象,反之,将把这个字符串放入池中,并返回。
可以通过一些简单的例子学习
package com.huyi.jvm;
/**
* Created with IntelliJ IDEA.
*
* @Author: huyi
* @Date: 2017/11/18 11:04
*/
public class StringIntern {
public static void main(String[] args) {
String a = new String("ab");
String b = new String("ab");
String c = "ab";
String d = "a" + "b";
String e = "b";
String f = "a" + e;
System.out.println(b.intern() == a);//false
System.out.println(b.intern() == c);//true
System.out.println(b.intern() == d);//true
System.out.println(b.intern() == f);//false
System.out.println(b.intern() == a.intern());//true
System.out.println(f.intern() == a.intern());//true
}
}
来分析下这个结果:
1. b.intern() == a ,首先a,b对象都是字符串对象,b.intern()返回的是字符串池的“ab”,"ab" == a 返回的肯定是false
2. b.intern() == c ,b.intern()返回的是字符串池的“ab”,"ab" == c,c 也是字符串常量“ab”,这里要说明的是对于字符串常量的比较 "abc" == ("a"+"bc") == ("ab"+"c"),==符号比较的是jvm虚拟机堆中的地址
3. b.intern() == d,原理和2相同,都是字符常量的比较
4. b.intern() == f,这里为什么是false呢,b.intern()返回的是字符串池的“ab”,而f是字符串对象,两者的地址不一致,所以为false
5. b.intern() == a.intern(),字符常量的比较,所以为true
6. f.intern() == a.intern(),字符常量的比较,所以为true
所以这里总结下:
- String.intern()方法返回的是一个字符串常量,这个常量如果已经在字符串池中存在,则直接返回,反之则保存后返回。
- String的 == 符号比较的是jvm虚拟机堆中的地址
参考:
https://www.cnblogs.com/wanlipeng/archive/2010/10/21/1857513.html
http://blog.csdn.net/chaofanwei/article/details/19486919