+ 2
Is it the case that More than one object creation is possible only in strings ?
What I mean is that when we write String str=new String("hello"); Then 2 objects are created one in heap and the same is copied in heap in string constant pool . So finally 2 objects are created And now reference type str points to object outside scp , So who will be pointing to object created in scp? Also is only string the case in which 2 objects are created?
2 Antworten
+ 2
Creation of duplicate objects is common in strings and is intentionally created whereas it might happen with objects of other types but there are good chances that those duplicates are not intentional.
A reference variable to a string object created using the new keyword will always point to the object on the heap and not in SCP. The string literal in the constant pool has an arbitrary reference which can be returned using the intern() method in the String class.
The below code will fetch the reference of "hello" created by the String str1 in constant pool and will assign it to str3.
https://code.sololearn.com/cR4JGlS1SxWD/?ref=app