java - 当我们使用 + 运算符连接时创建的新字符串对象在哪里

标签 java string string-concatenation

我知道这可能是非常基本的并且可能非常简单,但我无法清楚地理解在这种情况下会发生什么,所以,就这样吧。

在下面的代码中:

String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;

我知道 str1 和 str2 将在字符串常量池内部分别创建对象“Hello”和“World”。对于 str3,在 String Constant Pool 中创建了一个新对象,该对象指向在内部 String Constant 创建的“HelloWorld”游泳池

我的问题是,如果我连接 2 个或更多字符串(使用“+”或 concat() 方法)会发生什么情况?

是否会像 String str3 那样在池的外部创建一个新对象,或者 str4 会直接指向对象“HelloWorld”内部字符串常量池

PS : And IF it is the case similar as creation of new object outside the pool, then how does it happen without using the new keyword?

最佳答案

首先 String s = new String("abs"); 会创建两个对象,一个对象在池区,另一个在非池区,因为你用的是new以及作为参数的字符串文字。

String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;

到目前为止,您有五个 String 对象,四个在 String Constant Pool 中,一个在 Heap 中。所以你的 str4 是一个完全在字符串池中的新对象, 也请检查下面的代码,

 String str5="HelloWorld"; //This line will create one more String Constant Pool object because we are using the variable name as str5.
 String str6="HelloWorld";////This line will not create any object, this will refer the same object str5.

用于测试

System.out.println(str3==str4); //false
System.out.println(str4==str5);//false
System.out.println(str5==str6);//true

关于java - 当我们使用 + 运算符连接时创建的新字符串对象在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636396/

相关文章:

java - 在多线程中,getId方法如何确定任何线程的ID

java - 如何在 OSGI 中包含 slf4j-api、logback 和 slf4j.impl 的自定义实现?

swift - 从 Swift 中的字符串中删除某个字符后的所有字符

c# - 检查字符串的第一个元素是否为正整数

python - 疯狂的字符串连接

java - 无法发送 UDP 消息响应

Java - KeyListener - KeyReleased 有时不触发

java 如何直接将 double 转换为字符串?

C连接字符串变量字符串

jsf - EL中用于动态ResourceBundle键的字符串连接