java literals_java – 添加String Literals和String对象之间的区别

添加String Literal和String Object之间有什么区别?

例如

String s1 ="hello";

String s2 ="hello1";

String s3 ="hello" + "hello1";

String s4 ="hellohello1";

String s5 = s1 + s2;

System.out.println(s3 == s4); // returns true

System.out.println(s3 == s5); // return false

System.out.println(s4 == s5); // return false

为什么s3 / s4没有指向与s5相同的位置?

解决方法:

因为s1 s2不是常量表达式,因为s1和s2不是final,因此它的结果不是interned,即创建另一个对象来表示它,因此引用比较产生false.

String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are “interned” so as to share unique instances, using the method String.intern.

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

Simple names that refer to constant variables (§4.12.4).

如果将s1和s2声明为final,则s3 == s5将为true.

标签:java,string,literals

来源: https://codeday.me/bug/20190730/1578910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值