【发布时间】:2018-11-11 03:12:51
【问题描述】:
我有以下简单的 java 代码,我试图了解 java 中的字符串连接是如何使用 '+' 运算符工作的。
public class Problem {
public static void main(String... args){
String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object
System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false
}
}
str4 是 2 个字符串文字(ab 和 c)的结果,str5 是对 2 个字符串文字(str2 和 str3)的引用。在这两种情况下,java 都会调用 StringBuilder 类来执行连接。
而且我相信它应该会导致在 java 堆空间中创建 2 个不同的 StringBuilder 对象。
如果我的理解是正确的,为什么 str1 == str4 返回 true ?有人可以帮我弄清楚吗?
问候, 马尼什·夏尔马
【问题讨论】:
标签: string concatenation string-literals