Through decompilation, you can check the Java String and intern insider, and intern insider.

Source: Internet
Author: User

Through decompilation, you can check the Java String and intern insider, and intern insider.

I. String Problems

In our daily coding work, strings are very practical and easy to use. Therefore, few people have made some in-depth research on them. However, during the interview or written examination, it often involves in-depth and difficult questions. I occasionally ask questions about candidates during recruitment. It doesn't mean that they must be answered correctly or in depth. Generally, there are two purposes to ask these questions, the first is to evaluate the knowledge of the basic knowledge of JAVA, and the second is to examine the attitudes of candidates towards technology.

Let's see what the following program will output? If you can answer each question correctly and understand the cause, this article does not make much sense to you. If the answer is incorrect or is not clear about the principle, take a closer look at the following analysis. This article will help you understand the results of each program and the underlying reasons for outputting the results.

Code snippet 1:

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 2:

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 snippet 3 (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 snippet 3 (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 ease of description, the output result of the above Code is from #1 ~ #8 is encoded, and the blue font section below is the result.

Ii. In-depth string Analysis

1. Code segment 1 Analysis

A string does not belong to a basic type, but can be directly assigned with a literal value like a basic type. Of course, you can also generate a String object through new. However, the literal Assignment Method is essentially different from the new method to generate a string:

You can use the intern () method to add a string to the constant pool and return a reference pointing to the constant.

Now we should be clear about the result of code Segment 1:

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

Result #2: str2 calls the intern method and copies the str2 value ("string") to the constant pool. However, this string (that is, the string pointed to by str1) already exists in the constant pool ), therefore, the string reference is directly returned, so str1 = str2 returns true.

The following is the result of Running code 1:

2. Code Segment 2 Analysis

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

Constant pool content (Part ):

Result #3: str1 = str2 will certainly return true, because both str1 and str2 point to the same reference address in the constant pool. Therefore, after JAVA 1.6, the "+" operation of the constant string directly joins in the compilation phase to form a string.

13: new #4: generate the StringBuilder instance.

16: dup: Copy 13 to generate an object reference and press it into the stack.

17: invokespecial #5: Call the fifth item in the constant pool, that is, the StringBuilder. <init> method.

The above three commands are used to generate a StringBuilder object.

20: aload_1: load the value of the first parameter, that 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 to the stack.

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

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

32: astore 5: change the value of result reference in 29 to the fifth local variable, that is, assign a value to variable str3.

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

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

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

Result #5: str1 and str4 point to the third item in the constant pool, so str1 = str4 returns true. Here we can also find a phenomenon. For final fields, constants are directly replaced during the compilation period, while for non-final fields, values are assigned during the runtime.

38: new #9: Create a String object

41: dup: copy the reference and press it in the stack.

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

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

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

The 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 2. The output result is as follows:

3. Analysis of code Segment 3:

For code snippet 3, the running results in JDK 1.6 and JDK 1.7 are different. Let's take a look at the running results first, and then explain the reasons:

Result of JDK 1.6:

Result #7: In the first case, because the constant pool does not contain the string "str01", a reference to the "str01" in the heap is generated in the constant pool, when the literal value is assigned, the constant pool already exists, so you can directly return the reference. Therefore, both str1 and str2 point to the heap string and return true.

Result #8: After the positions are changed, the constant pool does not exist because the String str1 = "str01" does not exist in the constant pool, str2 points to the object in the heap. When the intern method is implemented, str1 and str2 are not affected, so false is returned.

 

Iii. FAQs

With understanding of the above knowledge, it is very easy to come and take a look at common interviews or pen tests:

 

Q: String s = new String ("xyz"), how many String objects are created?

A: Two: "xyz" in the constant pool and objects in the heap.

 

Q: output results of the following programs:

String s1 = "abc ";
String s2 = "abc ";
System. out. println (s1 = s2 );

A: true, all pointing to objects in the constant pool.

 

Q: output results of the following programs:

String s1 = new String ("abc ");
String s2 = new String ("abc ");
System. out. println (s1 = s2 );

A: false. Two references point to different objects in the heap.

 

Q: output results of the following programs:

String s1 = "abc ";
String s2 = "";
String s3 = "bc ";
String s4 = s2 + s3;
System. out. println (s1 = s4 );

A: false because s2 + s3 uses StringBuilder. append to generate different objects.

 

Q: output results of the following programs:

String s1 = "abc ";
Final String s2 = "";
Final String s3 = "bc ";
String s4 = s2 + s3;
System. out. println (s1 = s4 );

A: true. Because the final variable is directly replaced with the corresponding value after compilation, it is actually equivalent to s4 = "a" + "bc". In this case, the compiler will directly merge it into s4 = "abc", so the final s1 = s4.

 

Q: output results of the following programs:

String s = new String ("abc ");
String s1 = "abc ";
String s2 = new String ("abc ");

System. out. println (s = s1.intern ());
System. out. println (s = s2.intern ());
System. out. println (s1 = s2.intern ());

A: false, false, true. For more information, see section 2.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.