Confusion on string immutability

吃可爱长大的小学妹 提交于 2019-12-06 12:27:57

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

Mik378

1) Here String str is static, then where this object will be stored in memory?

Those literals will be stored in the String pool memory, no matter if the variable is declared as static or not.
More info here: Where does Java's String constant pool live, the heap or the stack?

2) Since String is immutable, where the object for "XYZ" will be stored?

Similar to the first answer: a literal will be stored in the pool memory. Immutability just allows the concept of shared pool memory.

3) Where will be final object will be Stored?

According to the Java specification, concatenation of literals will end up to a literal too (since known at compilation time), stored in the pool memory.
Excerpt:

"This is a " +        // actually a string-valued constant expression,
    "two-line string"    // formed from two string literals

4) And how will garbage collection will be done?

As essence of the pool memory, they won't be garbage collected by default. Indeed, if garbage collected immediately, the "shared" concept of the pool would fail.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!