java – String. How does Intern () work and how does it affect the string pool?

As we know, string() The intern () method adds a string value to the string pool if it does not already exist If it exists, the reference of the value / object is returned

String str = "Cat"; // creates new object in string pool  with same character sequence.  
String st1 = "Cat"; // has same reference of object in pool,just created in case of 'str'

 str == str1 //that's returns true

String test = new String("dog");
test.intern();// what this line of code do behind the scene

I need to know when I call test What will Intern () do?

Add "dog" with different references in the string pool or add test object references in the string pool (I don't think that's the case)?

I tried this

String test1 = "dog";

test == test1 // returns false

I just want to make sure that when I call test When intern(), it creates a new object with the same value in the string pool? Now I have two objects with a value of "dog" One exists directly in the heap and the other exists in the string pool?

Solution

It places the "dog" string in the string pool (unless it already exists) However, it does not necessarily put the object referred to in the test in the pool That's why you usually do this

test = test.intern();

Note that if your code has a "dog" literal, then "dog" already exists in the string pool, so test Intern() will return this object

Maybe your experiment puzzles you. In fact, you think of the following experiments:

String s1 = "dog";             // "dog" object from string pool
String s2 = new String("dog"); // new "dog" object on heap

System.out.println(s1 == s2);  // false

s2 = s2.intern();              // intern() returns the object from string pool

System.out.println(s1 == s2);  // true
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
分享
二维码
< <上一篇
下一篇>>