Parsing of string’s intern() method

1、 Overview

In the versions before and after JDK7, there are differences in the implementation of string's intern() method. The description environment of this paper is jdk8. The version differences of the intern() method will be explained at the end of this paper.

The intern () method is a native method that returns the string reference in the constant pool, which is mainly reflected in the following two points:

2、 Example description

Generally, there are three ways to create strings:

The literal creation method will create a string instance in the string constant pool and return the reference; Both new string() and StringBuilder / StringBuffer are created by creating a string instance on the heap and returning the reference.

public class StrIntrenTest {
    
    public static void main(String[] args) {
        // 1. 字面量创建形式
        String s1 = "jmcui";
        //  1. 在字符串常量池中生成字符串【"jmcui"】实例
        //  2. 将栈中的 s1 指向字符串常量池中的字符串【"jmcui"】实例

        System.out.println("s1 == s1.intern() :" + (s1 == s1.intern())); // true

        // 2. new 创建方式
        String s2 = new String("jmcui");
        //  1. 在Java堆中生成字符串【"jmcui"】实例
        //  2. 将栈中的 s2 指向Java堆中的字符串【"jmcui"】实例

        System.out.println("s1 == s2 :" + (s1 == s2)); // false
        System.out.println("s1.equals(s2) :" + s1.equals(s2)); // true
        System.out.println("s1 == s2.intern():" + (s1 == s2.intern())); // true

        // 3. StringBuilder/StringBuffer 方式和 new 方法类似
        String s3 = new StringBuilder("jm").append("cui").toString();
        //  1. 在Java堆中生成字符串【"jmcui"】实例
        //  2. 将栈中的 s3 指向Java堆中的字符串【"jmcui"】实例
        System.out.println("s1 == s3 :" + (s1 == s3)); // false
        System.out.println("s2 == s3 :" + (s2 == s3)); // false
        System.out.println("s2.intern() == s3.intern() :" + (s2.intern() == s3.intern())); // true
    }
}

3、 Version difference between and JDK6

The difference between the inter () method after JDK7 and the previous version is mainly reflected in the processing mechanism when the string does not exist in the constant pool.

In versions after JDK7, if the string does not exist in the constant pool, the object reference is added to the constant pool and returned. Note: Keyword - add object reference!

What about versions before JDK7? Its processing mechanism is to create a new string instance in the constant pool and return the instance reference if the string does not exist in the constant pool. Key words: new instance!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>