假设我有这个 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/