英文:
When a methd returns a String , will it be a literal or a String object?
问题
让我们假设有一个方法返回一个字符串。
String str = methodCall();
方法 methodCall() 的返回类型是 String。
我们会得到一个存在于池内存中的字符串字面值,还是只会得到一个字符串对象?
英文:
Lets say a method returns a String
String str = methodCall();
The return type of methodCall() is String.
Will we get a String literal which will be in pool memory or just a String object?
答案1
得分: 8
> 当一个方法返回一个字符串时,它是一个字面值还是一个字符串对象?
这个问题基于一个误解。
在运行时,每个 Java 字符串都被表示为一个 java.lang.String
对象。这包括字符串字面值。实际上,通常情况下无法区分一个起源于字符串字面值的 String
对象和其他方式产生的对象。
所以...基本上... 标题中的问题是没有意义的。
> 我们会得到一个在池内存中的字符串字面值还是一个字符串对象?
-
这取决于你返回的字符串是如何创建的。
-
并不是所有池中的对象都起源于字符串字面值。
-
通过调用
String.intern
方法可以将字符串添加到字符串池中。当字符串字面值被实体化时,JVM 会自动执行此操作,但在其他情况下不会自动执行。
因此,上述问题的答案是,方法返回的字符串对象如果它要么起源于字符串字面值,要么由某些应用代码通过调用 String.intern
方法放入字符串池中,那么它就会位于字符串池中。
最后,需要注意的是,在现代的 Java 应用程序和现代的 JVM 上,字符串池在很大程度上是不相关的:
- 自从 Java 7 开始,字符串池不再是一个单独的堆区域。
- 自从 Java 8 开始,字符串空间优化(去重)是由垃圾回收器本身执行得更加高效;参见 https://openjdk.java.net/jeps/192
调用 String.intern
总是一个相当可疑的优化,因为应用程序很少能够准确预测字符串对象的生命周期。对字符串进行内部化的缺点是/是字符串池索引会使用内存,并给垃圾回收器增加更多的工作。
英文:
> When a method returns a String, will it be a literal or a String object?
This question is based on a misconception.
At runtime, every Java string is represented as a java.lang.String
object. This includes string literals. In fact, it is (in general) impossible to distinguish a String
object that originated from a string literal from one that originated some other way.
So ... basically ... the question in the title does not make sense.
> Will we get a String literal which will be in pool memory or just a String object?
-
It depends on how the string that you are returning was created.
-
Not all objects in the string pool originated from string literals.
-
Strings may be added to the string pool by calling
String.intern
. The JVM does this automatically when string literals are reified, but it doesn't do it automatically under any other circumstances.
So, the answer to the above will be that a string object returned by a method will be in the string pool if EITHER it started life as a string literal OR some application code put it there by calling String.intern
.
Finally, note that the string pool is largely irrelevant to modern Java applications on modern JVMs:
- Since Java 7, the string pool is no longer a separate heap region.
- Since Java 8, string space optimization (de-duplication) is performed more efficiently by the GC itself; see https://openjdk.java.net/jeps/192
Calling String.intern
was always a rather dubious optimization because it is rarely possible for an application to accurately predict the lifetime of string objects. The downside of interning a string was / is that the string pool indexes use memory, and make more work for the garbage collector.
答案2
得分: 0
我认为这取决于methodCall()字符串。
英文:
I think it depends on the methodCall() string .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论