Java new String and new StringBuilder in heap behavior(堆行为中的 Java new String 和 new StringBuilder)
问题描述
- 字符串池是否驻留在堆上?如果是,字符串字面量是否符合垃圾回收条件?
当使用 new String("abc") 时,我们知道它在堆上创建了一个对象,并将字符串字面量放入字符串池中.所以我的第二个问题是:
When using new String("abc"), we know that it creates an object on the heap and places the String literal in the String pool. So my 2nd question is:
new StringBuilder("abc")的行为方式是否与new String("abc")相同?如果是,StringBuilder 如何操作字符串池中的字符串字面量?
- Does
new StringBuilder("abc")behave the same way asnew String("abc")? If yes, how does StringBuilder manipulate the String literal inside the String pool?
推荐答案
你混淆了编译时间、加载时间和运行时间.
You are confusing compile time, load time, and runtime.
在类加载时将字符串文字添加到常量池中.只需在类代码中的任何地方提及文字就足够了;您甚至不必在该类中执行任何代码行.
A string literal is added to the constant pool at class loading time. Just a mention of a literal anywhere in the class code is enough; you don't even have to execute any line of code in that class.
另一方面,表达式 new String("literal") 每次计算时都会产生一个新的 String 实例.该实例与常量池中的实例不同,并且具有字符串值的副本.
On the other hand, the expression new String("literal") yields a new String instance each time it is evaluated. That instance is distinct from the one in the constant pool and has a copy of the string value.
StringBuilder 在这方面的行为与 String 完全相同:它使用字符串文字值的副本进行初始化.
StringBuilder acts exactly the same way as String in this respect: it is initialized with a copy of the string literal's value.
这篇关于堆行为中的 Java new String 和 new StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:堆行为中的 Java new String 和 new StringBuilder
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
