The moose likes Beginning Java and the fly likes asking about string creation with reference to pool Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "asking about string creation with reference to pool" Watch "asking about string creation with reference to pool" New topic

asking about string creation with reference to pool

kumar abhay
Ranch Hand

Joined: Oct 02, 2001
Posts: 53
hi there,
i hope that u ppl r fine,so here i m with a question regarding string,given below:
String st1="Hello world";
String st2=st1;
String st3=new string ("Hello world");
my question is that i created a string named st n assigned it to st1 is created in pool
st2 is assigned the same value as st1 st1 is referenced to st2.st3 is not created in pool.
Q.1 why st3 is not created in the pool(what r the reasons)
Q.2 where st3 is created (bec all String literals r saved in the pool side).
i hope that u ppl will respond me asap.
take care
with regards
kumar abhay
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
Kumar, s3 is not created/stored in the pool because you are actually newing up an object. i.e You are actually creating an object by using the "new" keyword, so you are actually calling a constructor. Objects created in this way are stored in an area of memory refered to as the "Heap"


So much trouble in the world -- Bob Marley
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Kumar,
The pool is created by the compiler. At compile time all string literals are placed into a "pool". This can be done by the compiler because strings are immutable. That means that once a string is created it can never be changed.
When you use the new operator you are requesting a new object be created and not just point to an existing one. The compiler can't just ignore the new operator because you have specified the same string to the constructor.
I agree. Here's the link:
subject: asking about string creation with reference to pool
It's not a secret anymore!