Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

java - How does String.intern() work and how does it affect the String pool?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...