java - 在内存中创建了多少个字符串?

标签 java concatenation heap-memory string-concatenation string-pool

假设我有这个 String 表达式

String hi = "Tom" + "Brady" + "Goat"

我知道字符串池“允许运行时通过在池中保留不可变字符串来节省内存”String Pool

将在字符串池中创建多少个字符串?

我最初的猜测是 5 - “Tom”“Brady”“Goat”“TomBrady”,"TomBradyGoat",因为 String 连接的操作顺序(从左到右?)或者它只是最终结果,"TomBradyGoat",即存储在字符串池中?

最佳答案

这里是一个常量表达式,由 JLS, Section 15.28 定义.

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)

  • Casts to primitive types and casts to type String (§15.16)

  • The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)

  • The multiplicative operators *, /, and % (§15.17)

  • The additive operators + and - (§15.18)

(其他可能性)

编译器确定表达式 "Tom"+ "Brady"+ "Goat" 是常量表达式,因此它将表达式本身计算为 "TomBradyGoat" .

JVM 在字符串池中只有一个字符串,"TomBradyGoat"

关于java - 在内存中创建了多少个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28729561/

相关文章:

Java 视频自动重新编码未按预期工作

java - @JsonProperty 未按预期工作

php - 删除列中的重复数据

java - 堆 vs 堆栈 vs 永久空间

c++仅分配函数调用返回的结构的一部分

Android Eclipse DDMS > Heap > 导致GC变灰

java - 在子接口(interface)中声明具有相同声明的通用方法的体系结构重要性是什么

java - Android 程序失败。没有错误,没有日志猫。没有任何线索

python - 如何在 Python 中连接列表和数据框以创建字典

mysql - sql-从链接创建类似目录的结构