Java String文字池和字符串对象 [英] Java String literal pool and string object

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

问题描述

我知道JVM维护了一个字符串文字池,以提高性能并维护JVM内存,并了解到字符串文字是在字符串池中维护的。但我想澄清与堆上创建的字符串池和字符串对象相关的内容。

I have known that JVM maintains a string literal pool to increase performance and maintain JVM memory and learned that string literal is maintained in the string pool. But I want to clarify something related to the string pool and string object created on the heap.

如果我的解释错误,请纠正我。

Please correct me if my explanation is wrong.

String s = "abc";

如果执行上面的行,abc字符串文字会被添加到字符串池中池中不存在。并且在堆上创建字符串对象,并且引用 s 将指向池中的文字。

If the above line is executed, "abc" string literal is added to the string pool if it does not exist in the pool. And string object is created on the heap and a reference s will point to the literal in the pool.

问题:


  1. 此代码是否每次都在堆上创建字符串对象它被执行了吗?

  2. 字符串文字池是仅维护字符串文字还是维护字符串对象?

  3. JVM何时决定是否需要将字符串文字添加到字符串池中?它是在编译时还是运行时决定的?

如果指向字符串文字,我不确定字符串对象的确切位置在哪里在泳池里。

I am not sure where exactly string object is created if it points to a string literal in the pool.

谢谢。

推荐答案

没有文字池。 Interned Strings只是普通的堆对象。它们可能最终会出现在PermGen中,但即便如此,它们最终也可能被垃圾收集。

There is no "literal pool". Interned Strings are just normal heap objects. They may end up in the PermGen, but even then, they could eventually be garbage-collected.

类文件有一个常量池,其中包含用于的字符串文字班级。加载类时,会根据该数据创建String对象,这可能与String #intern的内容非常相似。

The class file has a constant pool, which contains the String literals used in the class. When the class is loaded, String objects are created from that data, which is probably very similar to what String#intern does.


这段代码每次执行时都会在堆上创建字符串对象吗?

Does this code create string object on the heap every time it is executed?

没有。将有一个正在重用的String对象。它是在加载类时创建的。

No. There will be one String object that is being reused. It has been created when the class was loaded.


字符串文字池是仅维护字符串文字还是维护字符串对象?

Does string literal pool maintain only string literals or does it maintain string object as well?

你也可以实习字符串。我认为他们的待遇大致相同。

You can intern Strings as well. I assume that they are treated more or less the same.


JVM何时决定是否需要将字符串文字添加到字符串池中?它是在编译时还是运行时决定的?

When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?

文字总是汇集。其他字符串需要在其上调用实习生。所以在某种程度上,决定是在编译时做出的。

Literals are always "pooled". Other Strings need to have "intern" called on them. So in a way, the decision is made at compile-time.

这篇关于Java String文字池和字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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