Which is better and why a = new String("AA") or a = "AA"
Hi,
Which is better and why
String a = new String("AA") or
String a = "AA"
Does invoking a construtor waste memory? Please explain in detail.
Thanks in advance
Deepak
Hi,
Which is better and why
String a = new String("AA") or
String a = "AA"
Does invoking a construtor waste memory? Please explain in detail.
Thanks in advance
Deepak
Actually we have a special memory for storing strings called "stringpool"
If we use a=new String("AA") two objects will get created,one in the string pool and another in the memory,and the reference variable will point to the object in the memory not to the object in the pool.
If we use a="AA",only one object will get created in the pool and the referencr variable will point to that object.
One more important point is that there is no duplication of objcets in the Stringpool
> Actually we have a special memory for storing strings
> called "stringpool"
> If we use a=new String("AA") two objects will get
> created,one in the string pool and another in the
> memory,
Executing that line only creates one, because of the new. The one in the constant pool was created when the class was loaded.
> If we use a=new String("AA") two objects will get
> created,one in the string pool and another in the
> memory
Could you explain more on this? I am wondering why it is creating inside string pool?
> Could you explain more on this? I am wondering why it
> is creating inside string pool?
here read this about string pool:
http://forum.java.sun.com/thread.jspa?forumID=31&threadID=5192307
The stuffs with creating declaring a string object with new or with out new operator is fine.
But my question is with what Padma has posted
> If we use a=new String("AA") two objects will get
> created,one in the string pool and another in the
> memory
So in case "AA" not there in string pool, does new creates "AA" on string pool as well as heap memory?
Please correct me..
All you need to know is that it's almost always wrong to use the constructor of java.lang.String that takes a String as an argument. There are times when you may want to, but you'll know when they are simply through experience. Worrying about the memory usage of it is a waste of time
> So in case "AA" not there in string pool,
That is not correct.
> does new creates "AA" on string pool as well as heap memory?
Yes. The literal "AA" points to a pooled String object. The new operator creates a new String object with the same character sequence ("AA"). You can verify this with a little code...
String s = new String("AA");
assert s != "AA";
assert s.equals("AA");
assert s.intern() == "AA";
~