dilip IneverGiveUp wrote:Hi Guys I am planning to give OCPJP exam. I ve been preparing for last one month and am new to this site as well.I want to know the difference between :
String s1 ="XYZ"; // and
String s2= new String("XYZ");
what i know is "new" is used to call the constructor to create the object and initiallise the instance variables, so what happens in the first case are we not creating object?Or are they both same.Please clear the doubt.
Tell the difficulties that i am difficult.
There is no difference,both will create string object s1 and s2.....
Thanks & Regards, Sumeet
SCJP 1.4, SCWCD 5, LinkedIn Profile
Sumit Patil wrote:
There is no difference,both will create string object s1 and s2.....
Creating String without the use of new operator, the jvm will fetch the reference from the string memory pool (not sure what this is called), but if we make a object using new operator, the jvm will be forced to create a new object which will be placed in the heap memory.
Tell the difficulties that i am difficult.
saloni jhanwar wrote:
Yes for string literal "XYZ" s1 object will be created on string literal pool and it is also a part of heap and for second new String("XYZ") s2 object will be created on heap but ultimately objects will be created
Thanks & Regards, Sumeet
SCJP 1.4, SCWCD 5, LinkedIn Profile
Sumit Patil wrote:
saloni jhanwar wrote:
Yes for string literal "XYZ" s1 object will be created on string literal pool and it is also a part of heap and for second new String("XYZ") s2 object will be created on heap but ultimately objects will be created
I agree both the objects would be created, but these 2 objects won't be the same, i.e s1 == s2 would be false
Tell the difficulties that i am difficult.
OCPJP 6 (91%)
saloni jhanwar wrote:
Yes, They have difference address then how they will be same ?
Thanks & Regards, Sumeet
SCJP 1.4, SCWCD 5, LinkedIn Profile
http://www.lifesbizzare.blogspot.com || OCJP:81%
Sumit Patil wrote:
saloni jhanwar wrote:
Yes, They have difference address then how they will be same ?
Now,s1 == s2 will be true, while s1 == s3 will be false.
s1 = "XYZ"
May or may not create a new String object.
If a String object with the literal "XYZ" already exists the reference 's1' will only point to it.
Since String objects are immutable.
Where as,
String s3 = new String("XYZ");
will always create a new Sting object.
More details here
Tell the difficulties that i am difficult.
John Jai wrote:Deviating from the topic There is a method intern() that searches the String pool for already created String before creating a new one. Discussed well in StringsLiterally
Sample Program for intern:
Don't get me started about those stupid light bulbs. |