Home > Java > javaTutorial > body text

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

Y2J
Release: 2017-05-19 09:47:33
Original
2376 people have browsed it

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
    }
}
Copy after login

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
    }
}
Copy after login

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
    }
}
Copy after login

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
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template