I have been reading Java String object and I had this question -
String x="a";
String y="b";
Does it create two objects in Java?
I have been reading Java String object and I had this question -
String x="a";
String y="b";
Does it create two objects in Java?
When ever a String is initialized using new operator its new object is created. Like if you do
String s1= new String ("string");
String s2=new String ("string");
String s3=new String ("string");
All of the three will create a separate String object in the heap. Whereas if all the above strings are initialized without new operator then, firstly the string will be checked in string pool for its existence. If required string exist then the new reference will start pointing to the existing string.Otherwise it will create new sting in the pool. For example:
String s1= "string";
String s2="string";
String s3="string1";
In the above example only two string will be created in string pool ("string" and "string1"). Where String s1 and s2 will refer to single object "string" and s3 will refer to another string object "string1".
String with literals gets created in String Pool. whereas String through new operators gets created in Heap Memory.
Advantage of creating String through literals is if that String value is already available in String Pool then you get the same reference where through new operator everytime you create a new object new reference.
In your case you will get same reference. so only object.
String object will be created by each line, unless they already exist in string pool...if they exist in string pool only a reference will be linked to your variable and no new objects will be created.
Those two lines of code will not create any objects. String literals such as
"a"
are put in the string pool and made available upon class loading.If you do
two objects will be created in runtime.
These questions/answers should cover follow-up questions: