String对象是如何在java中收集垃圾的? [英] How String object is garbage collected in java?

查看:150
本文介绍了String对象是如何在java中收集垃圾的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我们知道什么时候创建String对象,比如 String value = new String(ABC);
,那么新的将会创建String 对象,当我们再次使用value变量作为 value =xyz,那么一个新的 String 对象将被创建。



所以我的问题是,以前创建的 String 对象将被垃圾回收?

$每当你在JAVA中调用 new 时,它会在堆中创建一个对象,但在String的情况下文字,它将进入字符串常量池



示例代码:

 字符串值=新字符串(ABC); 
value =xyz;

现在在上面的示例代码中,ABC和xyz字符串文字将转到字符串常量Pool并且不会被垃圾收集,但最后 value 指的是字符串常量池中的xyz。



所以基本上有3个对象,2个在字符串常量池中,1个在堆中。


以前创建的String对象将会是垃圾收集?

该对象由 new 创建,将被垃圾回收一次它的范围/寿命已经完成,或者没有提及访问它。它适用于包括字符串在内的所有对象。



由于引用将被指向现有的对象在下一行字符串常量轮询中的值为xyz,以便在堆中使用 new 的先前创建的对象符合垃圾回收条件,但不符合ABC字符串字面值,它仍然在字符串常量池中。






试着想象它。





阅读更多.. 。


As we know when ever we are creating String object like String value = new String("ABC"); then new String object will be created and when we use value variable again as value="xyz" then a new String object will be created.

So my question is that at which point previously created String object will be garbage collected?

解决方案

Whenever you call new in JAVA it create an object in heap but in case of String literals, it will go into the String Constant Pool.

Sample code:

String value = new String("ABC");
value = "xyz";

Now in the above sample code "ABC" and "xyz" string literals will go to the String Constant Pool and will not be garbage collected but finally value is referring to "xyz" from the String Constant Pool.

So basically there are 3 objects, 2 in the String Constant Pool and 1 in the heap.

at which point previously created String object will be garbage collected?

The object is created by new will be garbage collected once its scope/life is finished or there is no reference to access it. It's applicable similarly for all the objects including String as well.

Since the value reference will be pointed to the existing object with the value "xyz" within the string constant poll in the next line, so that previously created object using new in the heap is eligible for garbage collection but not "ABC" string literal that is still in the string constant pool.


Try to visualize it.

Read more...

这篇关于String对象是如何在java中收集垃圾的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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