-
Junior Member
Answer in Memory point of view
Friends tell me what is the difference between in declaring,
String a =" abc "; and String b= new String("xyz");
when we apply "==" and "equals()" on first string , it depicts they are equal. but it is not in the case of second string. why it is so ? plz answer in memory point of view ?
-
Contributing Member
Re: Answer in Memory point of view
Hi Santh Kumar,
Please,can u make the question somewhat clear?
Is it String b= new String("xyz") or String b= new String("abc");
What does it mean when you say "when we apply "==" and "equals()" on first string " ??
Thanks
Neelima
-
Junior Member
Re: Answer in Memory point of view
Hi Nelima ,
Just take four instance variables of type String .out of them two are similar
For Example,
String a=" 123 "; and String x=new String("456");
String b=" 123 "; and String y = new String("456");
when i compare 'a' and 'b' with "==" operator and "equals()" method , it returns "TRUE".
when i compare 'x' and 'y' with "==" operator , it returns "FALSE" and with "equals()" method ,it returns "TRUE" .
i checked these two on an IDE.
i though , there might some difference in creating Strings above said cases just initialization and with Object.
plz tell me the difference in creating the Strings .
with Regards,
santh kumar
-
Contributing Member
Re: Answer in Memory point of view
When dealing with Strings in Java,we will be having actually two types of memory.
One is ---- Heap space
Another one -- Literal Pool
Case 1:
--------
So,here,when we say
String a = “abc”
The string literal is placed in literal pool referenced by ‘a’
Again,when we say
String b = “abc”
One more string object will not be created as the string literal is same,but the no. of references it is being referenced will be increased by one.So,now b also refers to the same literal on that pool.
Case 2:
--------
And, String x = new String(“xyz”)
This creates two objects,one on the heap and other on pool.
String y = new String(“xyz”);
This creates two more objects again.
This is how memory will be allocated for the above two cases.
And the difference between “ = = “ and “ equals “ is that
a) = = checks whether they are referring to the same object
b) equals checks whether the objects(ie., contents) are equal.
So,
a = = b is true as they are both referring to the same object
a.equals(b) is true as the object is same which is “abc”
x = = y is false as they are not referring to the same object
x.equals(y) is true as the content is same which is “xyz”.
Let me know if anywhere i am wrong.
Thanks
Neelima
Last edited by neelim; 04-24-2007 at 08:35 AM.
-
Junior Member
Re: Answer in Memory point of view
Well Said Ms.Neelima .
Very sophisticated Answer. Hats off 2 U .
Thank u.
with regards,
santh
Last edited by santh kumar; 04-24-2007 at 08:53 AM.
Reason: spelling mistake
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules