Reprinted: Detailed explanation of the intern() method in JAVA

Reprinted in:


Many children's shoes may encounter the problem of string strings being equal in the Java test or written test. Today, let's talk about the
runtime data area in the JAVA virtual machine, including thread sharing: heap, method area and thread isolation. Of: program counter, Java virtual machine stack, local method stack. Among them, the method area contains a field called constant pool. Because the String type is used frequently, HotSpot puts it into the constant pool.

Intern()

It is explained in the book "In-depth Understanding of Java Virtual Machine":
String.intern() is a Native method, and its function is: if the character constant pool already contains a string equal to this String object, return it to the constant pool String reference, otherwise, put the new string into the constant pool, and return the reference of the new string.
Different versions of JAVA virtual machines may have different implementations of this method. Let's use an example to illustrate

package com.tangbaobao.test1;

import org.junit.jupiter.api.Test;

/**
 * 测试intern方法
 *
 * @create 2018/02/02 15:19
 *
 *
 **/
public class Test2 {
    
    
    @Test
    public void fun1(){
    
    
        String str1 = new StringBuilder("计算机").append("软件").toString();

        String str2 = new StringBuilder("Ja").append("va").toString();

        String str3 = "java";
        String str4 = new String("java");

        System.out.println(str1.intern() == str1);//因为之前没有所以创建的引用和intern()返回的引用相同

        System.out.println(str2.intern() == str2);//"java在StringBuilder()之前已经出现过",所以intern()返回的引用与新创建的引用不是同一个

        System.out.println(str3 == str4);

    }
}


return result:

true
false
false

Guess you like

Origin blog.csdn.net/qq_36256590/article/details/132345017