Java字符串问题

标签 java string

我运行了以下程序,

    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 运算符初始化的字符串?

最佳答案

池仅与字符串文字相关 - 所以 firstStringsecondString 实际上是同一个对象 - 而在 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/

相关文章:

c - 字符串运行时错误仅适用于 getchar 为什么?

c - 需要基本食品银行计划帮助

java - 了解如何解耦

java - Play 框架和 Office 365 OAuth

java - 如何生成指定范围内的随机整数,可被 5 整除?

r - Hotelling 多元控制图

c++ - 比较两个字符串并从字符串 1 中删除相同的字符并使用 C++ 打印字符串 2

Python正则表达式字符串搜索返回起始索引

Java字符串修剪没有效果

java - youTube 数据 API V3 - 使用 PublishedAfter 时搜索返回错误 400