gpt4 book ai didi

java - 字符串池内存分配

转载 作者:行者123 更新时间:2023-11-29 03:11:42 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com