我运行了以下程序,
String firstString = "String";
String secondString = "String";
String thirdString = new String("String");
System.out.println(firstString == secondString);
System.out.println(firstString == thirdString);
System.out.println(firstString.intern() == thirdString);
System.out.println(firstString.intern() == thirdString.intern());
System.out.println(firstString.intern().equals(thirdString.intern()));
System.out.println(firstString == thirdString);
我的输出是
true
false
false
true
true
false
我了解到 jvm 将具有相同内容的字符串合并为相同的字符串。那正确吗?如果那是真的那么为什么 firstString == thirdString 不返回 false? jvm 是否仅汇集仅使用 :""而不是使用 new 运算符初始化的字符串?
最佳答案
池仅与字符串文字相关 - 所以 firstString
和 secondString
实际上是同一个对象 - 而在 thirdString
中你明确要求要在堆上创建的新对象。
我建议阅读有关 string literals in the spec 的部分.
它提供了有关如何以及何时合并字符串的更多信息。
另外,请注意本节末尾的这些项目符号:
- Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
- Literal strings within different classes in the same package represent references to the same String object.
- Literal strings within different classes in different packages likewise represent references to the same String object.
- Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
- Strings computed by concatenation at run time are newly created and therefore distinct.
关于Java字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339230/