微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java字符串相等示例

参见英文答案 > What is the Java string pool and how is “s” different from new String(“s”)?                                     5个
对不起事先提出基本问题,但有人可以解释一下原因:

String s = "lo";
String str7 = "Hel" + s;
String str8 = "He" + "llo";
System.out.println("str7 == str8 is " + (str7 == str8));

输出错误.
我认为str7和str8都指向String池中的同一个对象,因为字符串是不可变的.

我错了吗?
str7和str8都不在池中但在堆中吗?为什么?

当结果确实与字符串池中的不可变字符串相同时,能否请您提供一些字符串操作的示例?

PS:

String str9 = "He" +"llo";
System.out.println("str8 == str9 is " + (str9 == str8));

输出为真

解决方法

如果池中所有文字都进入字符串池,您的理解是正确的.

当你进行连接时会出现混乱.以下是需要注意的两点.

1)如果String在编译时解析,是,它与String池同步并使用相同的文字.对于前者

String str7 = "Helllo";
String str8 = "He" + "llo";

请注意,两者都是普通的文字.因此没有运行时转换等.

2)如果String在运行时解析,它会在运行时解析为一个新字符串,并且与其他任何其他字符串不同,除非您使用.equals方法来比较其内容.

String str7 = "Hel" + s;
String str8 = "He" + "llo";
System.out.println("str7 == str8 is " + (str7 == str8)); //false

在这种情况下,concat字符串with()运算符,JVM返回新的StringBuilder(string …).toString()因为一个是普通文字而另一个是变量.

看看Java language specification

If only one operand expression is of type String,then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

评论中的问题:

does it mean that in case the string is produced as the product of concatenation of literals then the result is always the same string in the pool?

是的.记住,你的意思是编译时解析表达式(也就是常量表达式),而不是运行时.

And when we concatenate string literal with string object then the resulting string is always a new string object built by means of StringBuilder under the hood?

是的,返回了一个新的String.附加的JVM链接确认了这一点.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐