aspose file tools*
The moose likes Java in General and the fly likes String Pool Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String Pool" Watch "String Pool" New topic
Author

String Pool

Ravissant Saraswat
Greenhorn

Joined: Mar 15, 2010
Posts: 20
Hi Everyone,
I've read that when you create String objects using "new" , 2 objects are created one of which a pool object which is simply given to a reference when its attempted to create a similar literal string, without creating a new object. Could anyone please tell me why I'm getting false below when the content of the String("Ravissant") is the same for both the references?



Thanks!
Ravissant
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Using "new" creates a completely new reference. It is not using a String from the pool.
In your example, you have two objects created:
1. At Line 06, "Ravissant" is created in the pool
2. At Line 06, a new String object is created, whose value equals "Ravissant" (but different reference)
3. At Line 07, an object is referring to the "Ravissant" object in the pool.
So these are two different references.

What would happen if :


[My Blog]
All roads lead to JavaRanch
Ravissant Saraswat
Greenhorn

Joined: Mar 15, 2010
Posts: 20
Hi Christophe,
First of all, thanks for your prompt reply. Ok, so when we do : String s1 = new String("Ravissant");
1) Two objects are created.
2) s1 points to the heap object
3) The second object is the pool object isnt being pointed to by any reference(?)
4) Later, when we do String s2= "Ravissant" , that "dangling/unassigned" object is given to the s1 reference.

Please let me know if the above deductions are correct.

Thanks,
Ravissant
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

There's a ranch article about Strings here. I think it will clear your doubts.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Pool
 
Similar Threads
Immutability?
how many eligible for Garbage Collection
Why String Constructor exists in the API
Using the String
(== test on String) doubt