先说String,它是一个finally类,即不可被继承,其方法默认也是finally不可被重写。查看源码可知intern是一个内部方法,下面是jdk11里的原文:
/**
* 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.
* @jls 3.10.5 String Literals
*/
public native String intern();
这是一个native方法,由String类私有的维护这个String池,它保证池内每个数据都只有一份。若有新的String对象赋值会先在String池中查找该值是否存在,存在则直接将引用指向该值,不存在则创建新的值。注意,用new创建字符串会创建两个数据,一个在堆里创建,一个是在String池,创建后引用会指向堆中数据,调用intern方法后指向String池数据。
具体看下面的例子
String a = "asdf";
String b = "as";
String c = "df";
String d = b+c;
String e = "as"+"df";
String f = new String("asdf");
String g = new String("as")+new String("df");
String h = "as" + new String("df");
String i = new String("as") + "df";
String aa = "1111";
String bb = new String("11") + new String("11");
System.out.println("================"); // ================
System.out.println(a == d); // false 引用地址不同
System.out.println(a == e); // true 引用地址相同,String池只会维护一份数据,数据相同时直接修改引用不会新建相同的数据
System.out.println(d == e); // false
System.out.println(a == d.intern()); // true intern()指向String池中的值
System.out.println("================"); // ================
System.out.println(a == f); // false new在堆中创建,等号赋值在String池中
System.out.println(a == g); // false
System.out.println(a == h); // false
System.out.println(a == i); // false
System.out.println(a == f.intern()); // true 调用intern后引用就指向了String池中的数据
System.out.println(a == g.intern()); // true
System.out.println(a == h.intern()); // true
System.out.println(a == i.intern()); // true
System.out.println("================"); // ================
System.out.println(f == g); // false
System.out.println(f == d); // false
System.out.println(f.intern() == d); // false
System.out.println(f == d.intern()); // false
System.out.println(f.intern() == d.intern()); // true
System.out.println(aa == bb); // false
System.out.println(aa == bb.intern()); // true
System.out.println("================"); // ================