6

As we know, String().intern() method add String value in string pool if it's not already exist. If exists, it returns the reference of that 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'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.intern() what this intern method will do?

add "dog" with different reference in string pool or add test object reference in string pool(i think, it's not the case )?

I tried this

String test1 = "dog";

test == test1 // returns false

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Muneeb Nasir
  • 2,414
  • 4
  • 31
  • 54

1 Answers1

11

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

It will put the "dog" string in the string pool (unless it's already there). But it will not necessarily put the object that test refers to in the pool. This is why you typically do

test = test.intern();

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

Perhaps your experiment confuses you, and it was in fact the following experiment 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
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • So, now s2 pointing to an object exist in pool but not the object in heap? right ? BTW Thanks. I got my answer. – Muneeb Nasir Jun 19 '15 at 07:44
  • 1
    Yes. You're right. `s2.intern()` will return an object from the pool, so before `s2 = s2.intern()` the `s2` variable will point at an object on the heap, and afterwards it will point at an object from the pool. – aioobe Jun 19 '15 at 07:46