<Java学习笔记>字符串存储的进一步了解,字符串的拼接和intern()方法

本文探讨了Java中字符串的拼接与intern()方法的行为。在字面量拼接时,如果字符串常量池中已存在,将直接返回引用;而对于引用变量的拼接,会创建新的堆对象。在JDK 1.7及以上,intern()方法会检查常量池,若字符串不存在则添加并返回引用,否则返回已存在的引用。这导致了字符串比较结果的差异。
摘要由CSDN通过智能技术生成

基于前一篇博客,现在来看这样一段代码:

        String s1 = "hello";
        String s2 = "world";

        String s3 = "helloworld";
        String s4 = "hello" + "world";
        String s5 = s1 + "world";
        String s6 = "hello" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s3 == s7);//false

        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false

根据上一篇笔记,在执行s4 = "hello" + "world"之前,字符串常量池中已有"hello""world""helloworld"这些字符串。

s3 == s4:s4 = "hello" + "

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值