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/