字符串拼接原理及字符串中jvm中存储位置

10. StringTable · 语雀

/*        字符串拼接操作
        ● 常量与常量的拼接结果在常量池,原理是编译期优化
        ● 常量池中不会存在相同内容的变量
        ● 只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
        ● 如果拼接的结果调用intern()方法,则主动将常量池中还没有的字符串对象放入池中,并返回此对象地址
*/
        String s = new String("a")+new String("b");//new String ("ab")
        System.out.println(s =="ab");//false

        String s1 = new String("c")+new String("d");//此时堆内创建对象实例,但字符串常量池中并没有常量"cd"
        s1.intern();//将cd复制到常量池
        System.out.println(s1=="cd");//true

        String x="ef";
        String s2 = new String("e") + new String("f");
        s2.intern();
        System.out.println(s2 =="ef"); //false

        String s3 = new String("g") + new String("h");
        String s4 = s3.intern();
        System.out.println(s3=="gh");//true
        System.out.println(s3==s4);//true

        String s5 = new String("ij");//此时堆内创建对象实例,并且在字符串常量池中创建常量"ij"
        s5.intern();//不起作用
        System.out.println(s5=="ij");//false 堆中存在值为ij的对象,字符串常量池中存在字符串ij,这俩不是同一内存地址

        String s6="kl";//没有对象实例,只在字符串常量池中创建"kl"
        System.out.println(s6=="kl");//true

        String x1="abc";
        String x2="def";
        String x3=x1+x2;//只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
        System.out.println(x3=="abcdef");//false x3指向堆空间的对象实例,abcdef是字符串常量池中的字符串

        String y3="efg"+"hij";
        System.out.println(y3=="efghij");//true


        String z1="aabb";
        String z2="ccdd";
        String z3=z1+z2;//只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
        String z4= z3.intern();  //将z3对象的值复制到字符串常量池中z3的就指向了字符串常量池
        System.out.println(z3=="aabbccdd");//true x3与常量池中的字符串是相同的地址
        System.out.println(z4=="aabbccdd");//true x4是常量池中的字符串

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值