Here String str is static, then where this object will be stored in
memory?
String str
is not an object, it's a reference to an object. "ABC"
, "XYZ"
& "ABCXYZ"
are three distinct String objects. Thus, str
points to a string. You can change what it points to, but not that which it points at.
Since String is immutable, where the object for "XYZ" will be stored?
As explained in above & also by Mik378, "XYZ"
is just a String object which gets saved in the String pool memory and the reference to this memory is returned when "XYZ"
is declared or assigned to any other object.
Where will be final object will be Stored?
The final object, "ABCXYZ"
will also get saved to the pool memory and the reference will be returned to the object when the operation is assigned to any variable.
And how will garbage collection will be done?
String literals are interned. As of Java 7, the HotSpot JVM puts interned Strings in the heap, not permgen. In earlier versions of Java, JVM placed interned Strings in permgen. However, Strings in permgen were garbage collected. Apparently, Class objects in permgen are also collectable, so everything in permgen is collectable, though permgen collection might not be enabled by default in some old JVMs.
String literals, being interned, would be a reference held by the declaring Class object to the String object in the intern pool. So the interned literal String would only be collected if the Class object that referred to it were also collected.
Shishir