java - 字符串池内存分配

标签 java string string-pool

String s = "abc";
String s4 = s + "";
System.out.println(s4 == s);
System.out.println(s4.equals(s));

这打印:

false
true

谁能解释一下为什么会这样?

最佳答案

String s="abc"; // goes to string constants pool
String s4 = s +"" ;// has value "abc" but goes on heap and not in string constants pool
System.out.println(s4==s);//well,, the references are not equal. There are 2 diffrent instances with value="abc"
System.out.println(s4.equals(s)); // equals() checks for value and the values of both insatnces are equal.

关于java - 字符串池内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003888/

相关文章:

java - 如何从谷歌日历获取日期时间

java - 数数元音、辅音,并在字符串中打印它们的计数和乘积

java - 从java应用程序外部传递过来的String会保存在String池中吗?

java - 为什么使用 new 运算符创建的字符串会在字符串池中创建字符串文字

java - Spring 网 : Failed to register servlet with name 'dispatcher'

Java初学者(客户端-服务器): Sending multiple Integers to a socket

为每个字符 append 一个字符串的 Javascript 代码

string - 删除 Swift 中字符串开头的所有换行符

java - 如何将字符串添加到字符串池中

Java:java.util.ConcurrentModificationException 无法解释