对字符串不变性的困惑 [英] Confusion on string immutability

查看:151
本文介绍了对字符串不变性的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码: -

I have following code:-

public class StaticImplementer {
    private static String str= "ABC";
    public static void main(String args[]) {
        str = str + "XYZ";
    }
}

问题: -


  1. 这里String str是静态的,那么这个对象将存储在内存中?

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

由于String是不可变的,XYZ的对象将被存储在哪里?

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

最终对象将在哪里存储?

Where will be final object will be Stored?

垃圾收集将如何完成?


推荐答案


这里String str是静态的,那么这个对象将存储在
内存中?

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

字符串 str 不是对象,它是对象的引用。 ABCXYZ& ABCXYZ是三个不同的String对象。因此, str 指向一个字符串。您可以更改它指向的内容,但不能更改它指向的内容。

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.


由于String是不可变的,因此XYZ的对象将被存储?

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

如上所述&同样由Mik378,XYZ只是一个String对象,它保存在String池内存中,当XYZ时返回对该内存的引用被声明或分配给任何其他对象。

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?

最终对象ABCXYZ也将保存到池内存中当操作被分配给任何变量时,引用将返回给对象。

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?

字符串文字被实习。从Java 7开始,H​​otSpot JVM将实际的字符串放入堆中,而不是permgen。在早期版本的Java中,JVM在permgen中放置了实际的字符串。然而,permgen的字符串被垃圾收集。显然,permgen中的Class对象也是可收集的,因此permgen中的所有内容都是可收集的,但默认情况下在某些旧JVM中可能不会启用permgen集合。

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.

字符串文字,即interned,将是由声明的Class对象保持在实习池中的String对象所持有的引用。因此,只有在收集引用它的Class对象时,才会收集实习文字字符串。

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

这篇关于对字符串不变性的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆