JDK中String类的intern方法实例

JDK的String类有一个intern方法:
public native 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>
...
*/

该方法的作用是将字符串加载到常量池中,如果常量池中有数据,则直接取常量池中的数据,如果常量池中如果没有数据,则将数据写入常量池并返回常量池中的数据。
JDK1.6常量池位于方法区,JDK1.7以后常量池位于堆。

写3段代码测试下:

public static void test_intern_1() {
    String s1 = new String("123") + new String("123");
    s1.intern();
    String s2 = "123123";
    // true in JDK1.8
    System.out.println(s1 == s2);
}

在定义变量s2之前,调用s1.intern()方法将字符串123123复制到常量池,因此变量s1,s2指向相同引用。

public static void test_intern_2() {
    String s1 = new String("123") + new String("123");
    String s2 = "123123";
    s1.intern();
    // false in JDK1.8
    System.out.println(s1 == s2);
}

先定义定义变量s1s2,然后调用s1.intern()方法,但调用后未使用返回值,因此s1还是指向之前new String的引用。

public static void test_intern_3() {
    String s1 = new String("123") + new String("123");
    String s2 = "123123";
    s1 = s1.intern();
    // true in JDK1.8
    System.out.println(s1 == s2);
}

先定义定义变量s1s2,然后调用s1.intern()方法并且将返回值赋值给s1,由于s2已申明了字符串常量,
因此s1.intern()方法返回s2的引用,最终变量s1,s2指向相同引用。


参考:

原文地址:https://www.cnblogs.com/cdfive2018/p/14240503.html