search
HomeJavajavaTutorialIn-depth analysis of the intern() method in Java

1. String problem

Strings are actually very useful in our daily coding work, and they are relatively simple to use, so few people do anything special about them. Deep research. On the other hand, interviews or written tests often involve more in-depth and difficult questions. When recruiting, I occasionally ask candidates relevant questions. This does not mean that the answers must be particularly correct and in-depth. Usually, the purpose of asking these questions is two-fold. The first is to test the understanding of the basic knowledge of JAVA. The second is to test the basic knowledge of JAVA. The second is to examine the applicant's attitude towards technology.

Let’s see what the following program will output? If you can answer every question correctly and know why, this article won't mean much to you. If the answer is incorrect or the principle is not very clear, then take a closer look at the following analysis. This article should help you clearly understand the results of each program and the deep-seated reasons for outputting the results.

Code segment one:

package com.paddx.test.string;
public class StringTest {
    public static void main(String[] args) {
        String str1 = "string";
        String str2 = new String("string");
        String str3 = str2.intern();
 
        System.out.println(str1==str2);//#1
        System.out.println(str1==str3);//#2
    }
}

Code segment two:

package com.paddx.test.string;
public class StringTest01 {
    public static void main(String[] args) {
        String baseStr = "baseStr";
        final String baseFinalStr = "baseStr";
 
        String str1 = "baseStr01";
        String str2 = "baseStr"+"01";
        String str3 = baseStr + "01";
        String str4 = baseFinalStr+"01";
        String str5 = new String("baseStr01").intern();
 
        System.out.println(str1 == str2);//#3
        System.out.println(str1 == str3);//#4
        System.out.println(str1 == str4);//#5
        System.out.println(str1 == str5);//#6
    }
}

Code segment three (1):

package com.paddx.test.string;  
public class InternTest {
    public static void main(String[] args) {
 
        String str2 = new String("str")+new String("01");
        str2.intern();
        String str1 = "str01";
        System.out.println(str2==str1);//#7
    }
}

Code segment three (2):

package com.paddx.test.string;
 
public class InternTest01 {
    public static void main(String[] args) {
        String str1 = "str01";
        String str2 = new String("str")+new String("01");
        str2.intern();
        System.out.println(str2 == str1);//#8
    }
}

For the convenience of description, I have encoded the output results of the above code from #1~#8, and the blue font part below is the result.

2. In-depth analysis of strings

1. Analysis of code segment 1

Strings do not belong to basic types, but they can be like basic types. Direct assignment through literals, of course, you can also use new to generate a string object . However, there is an essential difference between generating strings through literal assignment and new:

In-depth analysis of the intern() method in Java

When creating a string through literal assignment, priority will be given to constants Search the pool to see if the same string already exists. If it already exists, the reference in the stack directly points to the string; if it does not exist, a string is generated in the constant pool and then The reference on the stack points to this string. When creating a string through new, a string object is directly generated in the heap (note, after JDK 7, HotSpot has transferred the constant pool from the permanent generation to the heap. For detailed information, please refer to "JDK8 MemoryModel-The Disappearing PermGen" article), the reference in the stack points to the object. For string objects in the heap, you can add the string to the constant pool through the intern() method and return a reference to the constant.

Now we should be able to clearly understand the result of code segment 1:

Result #1: Because str1 points to a constant in the string, and str2 is an object generated in the heap, so str1==str2 returns false.

Result #2: str2 calls the intern method, which will copy the value in str2 ("string") to the constant pool, but the string already exists in the constant pool (that is, the string pointed to by str1), so Returns a reference to the string directly, so str1==str2 returns true.

The following is the result of running code segment one:

In-depth analysis of the intern() method in Java

2. Analysis of code segment two

For The result of code segment 2 is easier to understand by decompiling the StringTest01.class file:

Constant pool content (part):

In-depth analysis of the intern() method in Java

Execution instructions (part) , the second column #+ordinal corresponds to the item in the constant pool):

In-depth analysis of the intern() method in Java

Before explaining the above execution process, first understand the two instructions:

ldc : Push item from run-time constant pool, load the reference of the specified item from the constant pool to the stack.

astore_:Store reference into local variable, assign the reference to the nth local variable.

Now we begin to explain the execution process of code segment 2:

0: ldc             #2: Load the second item ("baseStr") in the constant pool into the stack.

2: astore_1 : Assign the reference in 1 to the first local variable, that is, String baseStr = "baseStr";

3: ldc #2: Load the second variable in the constant pool item("baseStr") onto the stack.

5: astore_2 : Assign the reference in 3 to the second local variable, that is, final String baseFinalStr="baseStr";

6: ldc #3: Load the first string in the constant pool Three items ("baseStr01") are added to the stack.

8: astore_3: Assign the reference in 6 to the third local variable, namely String str1="baseStr01";

9: ldc #3: Load the third item ("baseStr01") in the constant pool into the stack.

11: astore 4: Assign the reference in 9 to the fourth local variable: String str2="baseStr01";

Result #3: str1==str2 will definitely return true , because both str1 and str2 point to the same reference address in the constant pool. So in fact, after JAVA 1.6, the "+" operation of a constant string will be directly synthesized into a string during the compilation phase.

13: new #4: Generate an instance of StringBuilder.

16: dup: Copy the reference of the object generated by 13 and push it onto the stack.

17: invokespecial #5: Call the fifth item in the constant pool, the StringBuilder. method.

The function of the above three instructions is to generate a StringBuilder object.

20: aload_1: Load the value of the first parameter, which is "baseStr"

21: invokevirtual #6: Call the append method of the StringBuilder object.

24: ldc #7: Load the seventh item ("01") in the constant pool into the stack.

26: invokevirtual #6: Call the StringBuilder.append method.

29: invokevirtual #8: Call the StringBuilder.toString method.

32: astore 5: Change the result reference assignment in 29 to the fifth local variable, that is, the assignment to variable str3.

Result #4: Because str3 is actually the result generated by stringBuilder.append(), it is not equal to str1, and the result returns false.

34: ldc #3: Load the third item ("baseStr01") in the constant pool into the stack.

36: astore 6: Assign the reference in 34 to the sixth local variable, that is, str4="baseStr01";

Result #5: Because str1 and str4 point to constants The third item in the pool, so str1==str4 returns true. Here we can also find a phenomenon. For final fields, constant replacement is directly performed at compile time, while for non-final fields, assignment processing is performed at runtime.

38: new

42: ldc #3: Load the third item ("baseStr01") in the constant pool into the stack.

44: invokespecial #10: Call the String."" method, and pass the reference in step 42 as a parameter to the method.

47: invokevirtual #11: Call the String.intern method.

The corresponding source code from 38 to 41 is new String(“baseStr01″).intern().

50: astore 7: Assign the result returned in step 47 to variable 7, that is, str5 points to the position of baseStr01 in the constant pool.

Result #6: Because both str5 and str1 point to the same string in the constant pool, str1==str5 returns true.

Run code segment two, the output result is as follows:

In-depth analysis of the intern() method in Java

3. Analysis of code segment three:

For Code segment three has different running results in JDK 1.6 and JDK 1.7. Let’s take a look at the running results first, and then explain the reasons:

Running results under JDK 1.6:

In-depth analysis of the intern() method in Java Running results under JDK 1.7:

In-depth analysis of the intern() method in JavaAccording to the analysis of code segment 1, it should be easy to get the result of JDK 1.6, because str2 and str1 originally point to different locations and should return false.

The strange problem is that after JDK 1.7, true is returned for the first case, but after changing the position, the returned result becomes false. The main reason for this is that after JDK 1.7, HotSpot moved the constant pool from the permanent generation to the metaspace. Because of this, the intern method after JDK 1.7 has undergone relatively large changes in implementation. After JDK 1.7, the intern method will still be used first. Go to

to query whether

already exists in the constant pool. If it exists, return the reference in the constant pool. This is no different from before. The difference is that if the corresponding string cannot be found in the constant pool, then The string will no longer be copied to the constant pool, but a reference to the original string will be generated in the constant pool. So: Result #7: In the first case, because there is no string "str01" in the constant pool, a reference to "str01" in the heap will be generated in the constant pool, and When performing literal assignment, the constant pool already exists, so the reference can be returned directly. Therefore, str1 and str2 both point to the string in the heap and return true.

Result #8: After swapping the positions, because the constant pool does not exist when performing literal assignment (String str1 = "str01"), str1 points to the position in the constant pool, and str2 points to the heap. When the intern method is used for the object in , it has no effect on str1 and str2, so false is returned.

【Related recommendations】

1. Java free video tutorial

2. Summary of experience in using the intern() method in JAVA

3. What is the concept of intern method in java

4. Analysis of the role of intern() in Java

5. Detailed explanation of intern() in String object

The above is the detailed content of In-depth analysis of the intern() method in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),