Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - How String Literal Pool Works

String str = new String("Hello");

Normally I have read, in many articles available on internet, that two objects are created when we write the statement above. One String object is created on the heap and one string object is created on the Literal Pool. And the heap object is also referring the object created on Literal Pool. (Please correct this statement of mine if it is wrong.)

Please note that the above explanation is as per my understanding after reading some articles on internet.

So my question is.. Are there any ways available to stop creating the string object in literal pool. How it can be done?

[Please let me know about the best link for understanding of this Literal Pool, How is it implemented]

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There's only ever be one string with the contents "Hello" in the literal pool. Any code which uses a string constant with the value "Hello" will share a reference to that object. So normally your statement would create one new String object each time it executed. That String constructor will (IIRC) create a copy of the underlying data from the string reference passed into it, so actually by the time the constructor has completed, the two objects will have no references in common. (That's an implementation detail, admittedly. It makes sense when the string reference you pass in is a view onto a larger char[] - one reason for calling this constructor is to avoid hanging onto a large char[] unnecessarily.)

The string pool is used to reduce the number of objects created due to constant string expressions in code. For example:

String a = "Hello";
String b = "He" + "llo";
String c = new String(a);

boolean ab = a == b; // Guaranteed to be true
boolean ac = a == c; // Guaranteed to be false

So a and b refer to the same string object (from the pool) but c refers to a different object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...