Reputation: 7067
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]
Upvotes: 4
Views: 2487
Reputation: 2113
If I understand your question correctly, you're asking how to initialize a string without placing it in the string literal pool. You can avoid this as long as you don't declare a string literal expression (don't declare a series of characters in double quotes.)
// these two strings will be placed in the string literal pool
String one = "one";
String two = new String("two");
// this third string will NOT be placed in the string literal pool
String three = new String(new char[] {'t', 'h', 'r', 'e', 'e'});
Upvotes: 2
Reputation: 1500575
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.
Upvotes: 6