java - 在 String 字面值和 new String 对象之间创建了多少个对象

标签 java string-literals

我对下面的例子感到困惑。我想知道运行此代码后将在内存中创建多少个对象。请尽可能向我解释详细信息。

String firstName= "Mr.Z";
String secondName= firstName + "Beyond";
String thirdName= secondName + "Plus";
String newName= new String("Mr.Z");

最佳答案

下面的链接应该可以消除您对字符串文字和字符串对象创建概念的所有疑问。

http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

When you create a String using a String Literal, the object is created on the heap and the reference to that object is stored in the String Constant Pool. Hereafter, any references to that String literal will not create new object but the reference from the String Constant Pool is returned. When you create a String object using a new keyword, the object is created on heap but no references are stored in the String Constant Pool.

In your case: 4 objects shall be created on the heap but only the references of the first three objects will be stored in the String Constant Pool. The object created using the new keyword will not have its reference stored in the String Constant Pool

关于java - 在 String 字面值和 new String 对象之间创建了多少个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739858/

相关文章:

c# - 字符串字面量识别问题

c# - 在 C++ 中创建原始文本字符串,类似于 C#'s "@string"

c++ - 如何正确覆盖文字运算符?

java - 没有双变量的相同代码

java - 需要 SQLite 查询帮助

java - 将超链接放在数组列表中

java - 抽象类扩展具体类

可以修改 C 中的字符串文字吗?

c++ - C编译器??)替换

java - For 循环内的 Firestore 查询