String and new String("')
Hi Friends,
Hope you all are doing good!
String str1 = new String ("abc");
String str2 = "bcd";
The first one is an object and the second one a variable.
Is the second one a primitive one?
How is the storage for both cases handeled?
I mean is it right to say that first one is stored on HEAP since all objects are stored on HEAP.
While the second is stored on STACK (But i think this is wrong and a bit confusing)..
Would appreciate any replies from your side
Thanks,
Vishal
[547 byte] By [
Vishal.MKa] at [2007-10-2 20:11:13]

Hi vishal,
String str1 = new String ("abc");
String str2 = "bcd";
infact both are one and the same. in the second sentence, is executed it interanlly creates an object of string and assigns "bcd" to that string something like
String Dummy = new String("bcd");
So cdoing either way makes no difference.
SHLa at 2007-7-13 22:51:47 >

> So cdoing either way makes no difference.
Not really. This has been discussed billion times in these fora:
[url=http://forum.java.sun.com/thread.jspa?forumID=31&threadID=680968]Difference between String s = "DDD" to String s=new String("DDD")[/url]
[url=http://forum.java.sun.com/thread.jspa?forumID=31&threadID=671234]difference b/w String and new String()[/url]
[url=http://forum.java.sun.com/thread.jspa?forumID=31&threadID=632051]String str=new String("My String") v.s. String str="My String";[/url]
[url=http://onesearch.sun.com/search/onesearch/index.jsp?qt=new+String%28&charset=UTF-8&rf=0&subCat=siteforumid%3Ajava31&rt=1&site=dev&nh=10&cs=0&y=8&dftab=siteforumid%3Ajava31&chooseCat=javaall&x=6&col=developer-forums]etc.[/url]
> Hi Friends,
> Hope you all are doing good!
>
> String str1 = new String ("abc");
> String str2 = "bcd";
>
> The first one is an object and the second one a
> variable.
>
No.
Both str1 and str2 are variables of type reference to String.
In both cases, the right hand side evaluates to a reference to a String object.
In the first case, the reference just points directly to the String object "abc" in the constant pool. In the second case, a new String object is created.
> I mean is it right to say that first one is stored
> on HEAP since all objects are stored on HEAP.
>
> While the second is stored on STACK (But i think this
> is wrong and a bit confusing)..
The reference variables str1 and str2 are stored on the stack if they're declared inside a method, and they're stored on the heap inside their enclosing object if they're member variables.
The String objects are stored on the heap.
jverda at 2007-7-13 22:51:47 >

Thanks jverd for your response.
You mean to say that:-
str1 and str2 stay on STACK
str1 is on STACK and points to an adress on HEAP which in turn points to the actual value "abc" in memory.
While str2 is on STACK and directly points to the value "bcd" on HEAP.
I think this "bcd" should be on STACK.
Am I right?
Vishal