考虑下面的代码:
- 如何在不使用
new String()
的情况下创建str1
对象? - 为什么
str1
和str2
对象引用相同的内存位置?
String str1 = "hello";
String str2 = "hello";
最佳答案
java语言规范中都有描述。
Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
关于java - Java中字符串初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8903753/