gpt4 book ai didi

java - 当我们创建一个新的 String 对象时,在构造函数中传递的 String 文字存储在哪里

转载 作者:行者123 更新时间:2023-11-29 03:07:21 24 4
gpt4 key购买 nike

用 Java 编写

String S1 = "TestString";
String S2 = "TestString";

然后与 if(S1==S2) 比较,我们得到 true 作为 boolean 结果。相同的解释是字符串常量是在字符串池中创建的,因此 S1 和 S2 在这里引用的是同一个字符串常量。另外,如果我们写类似的东西

String S1 = new String("TestString");

String S2 = new String("TestString");

然后与 if(S1==S2) 进行比较,我们得到 false。原因是 S1 和 S2 的引用不同,因为字符串文字是在堆中创建的。

我的问题是,在构造函数中传递的字符串文字“TestString”在哪里创建?它与字符串文字/常量相同吗?因此应该像案例 1 一样在 Pool 中创建?如果是,那么当我们在上面两个语句之后写类似的东西时

String S3 = "TestString";

这不应该创建一个新的字符串文字,比较 if(S1==S3) 应该给我 true 但它给出 false。

所以我无法弄清楚这个字符串文字是在何时何地传递到构造函数中创建的。

如有任何帮助,我们将不胜感激。谢谢

最佳答案

My Question is that where was the String literal "TestString" which was passed in the constructor created? Is it same as a String literal/constant? and hence should be created in the Pool as was in the case 1 ?

正确,传递给构造函数调用的常量字符串new String("TestString")存储在字符串池中,就像语句String S1 = "TestString"中一样.

String S1 = new String("TestString");

String S2 = new String("TestString");

String S3 = "TestString";

在这种情况下 S1==S3给出 false 因为 S3引用由用于 S1 的构造函数的参数创建的字符串文字,而 S1是一个不同的字符串(因为它是用构造函数创建的)。

关于java - 当我们创建一个新的 String 对象时,在构造函数中传递的 String 文字存储在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com