加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java字符串相等示例

发布时间:2020-12-15 04:38:47 所属栏目: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"
参见英文答案 > 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链接确认了这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读