面试题: 以下两行代码共创建了几个String字符串对象 ?

		String s8 = new String("girlfriend");
        String s9 = new String("girl" + "friend");
答案:  3个
原因:
首先 : "girlfriend" 在常量池中不存在, 故创建一个字符串对象
其次 : new String("girlfriend") : 表示new 了一个字符串对象
然而 : "girl" + "friend" 由于是两个常量使用+号拼接, 在javac编译时, 会自动进行调优, 使得"girl" + "friend" == "girlfriend" , 而"girlfriend" 在常量池中已经存在, 故只需要引用赋值, 不需要创建新的
最后 : new String("girl" + "friend") : 表示new 了一个字符串对象
综上所述 : 共创建了3个字符串对象
相关笔记
public static void main(String[] args) {
        // 定义两个字符串
        // "helloworld" 会存储到堆区中的常量池中,将索引值赋值给s1
        String s1 = "helloworld";
        // "helloworld"已经存在常量池中, 不会再重新创建, 将索引值给s2
        String s2 = "helloworld";
        System.out.println("s1 == s2 = " + (s1 == s2));
        System.out.println(s1 == s2); // 故判断结果为 true

        // 定义字符串
        String s3 = "hello";  //"hello"在常量池中不存在, 故重新创建, 并将索引值给s3
        String s4 = s3 + "world"; // s3是变量, 无法用到编译优化 , "world"不在常量池中,故需要创建 ,使用+号对string连接 , 会在 堆区 创建一个 新的字符串对象 , 故会是一个新的引用值 给 s4
        System.out.println(s1 == s4);  // 故 s1 和 s4 的码值不同 false

        String s5 = "hello" + "world"; // javac编译器会对字符串 常量的连接 进行优化 , 在.Java -> .class的这个过程中优化,故 s5 其实就是 s5 = "helloworld"
        System.out.println(s1 == s5);  // true
        System.out.println(s4 == s5);  // false

        // final 常量
        final String s6 = "hello"; // "hello"在常量池中已经存在, 故直接引用值 赋给 s6
        String s7 = s6 + "world";   // "world"已经在常量池中, 不需要创建,只需要调用,  因为s6是个常量 , 故javac编译器会对字符串 进行优化 => 即 s6 + "world" == "helloworld" , 然后又发现"helloworld"在常量池中已经存在 , 故直接将 引用值 赋 给 s7
        System.out.println("s1 == s7 = " + (s1 == s7));  // true
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值