How does String.intern () work and how does this affect the string pool?

As you know, the String().intern() method adds a String value to the string pool if it does not already exist. If exists, it returns a reference to this value / object.

 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 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.intern() , what will this intern method do?

add a "dog" with a different link in the row pool or add a link to the test object in the row pool (I think this is not so)?

I tried this

 String test1 = "dog"; test == test1 // returns false 

I just want to make sure when I call test.intern() , it creates a new object with the same value in the String pool? I now have 2 objects with the value "dog". Does one exist directly on the heap and the other on String?

+6
source share
1 answer

when I call test.intern() , what will this intern method do?

It will put the string "dog" in the string pool (if it does not already exist). But it will not necessarily place the object that test denotes in the pool. That's why you usually do

 test = test.intern(); 

Note that if there is a literal "dog" in your code, then there will be "dog" in the string pool, so test.intern() will return this object.

Perhaps your experiment confuses you, and in fact it was the next experiment that you had in mind:

 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 
+11
source

Source: https://habr.com/ru/post/989381/


All Articles