我知道这可能是非常基本的并且可能非常简单,但我无法清楚地理解在这种情况下会发生什么,所以,就这样吧。
在下面的代码中:
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/