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

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

发布时间:2020-12-15 08:39:36 所属栏目:Java 来源:网络整理
导读:添加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(
添加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.

JLS 3.10.5 String Literals:

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.

JLS 15.28 Constant Expression:

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).

JLS 4.12.4定义了最终变量.

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

(编辑:李大同)

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

    推荐文章
      热点阅读