0
点赞
收藏
分享

微信扫一扫

String str = new String("xyz") 创建了几个对象?

扒皮狼 2021-09-25 阅读 54

看下下面的代码:

    public static void main(String[] args) {
        String str1 = "Hello";
        // System.identityHashCode(s) 方法可以返回对象内存地址,不管对象是否重写hashCode()方法
        System.out.println(System.identityHashCode(str1));// 1112280004

        str1 = "java";
        System.out.println(System.identityHashCode(str1));// 1013423070

        String str2 = "Hello";
        System.out.println(System.identityHashCode(str2));// 1112280004

        String str3 = new String("Hello");
        System.out.println(System.identityHashCode(str3));// 380936215

        String str4 = "Hello";
        System.out.println(System.identityHashCode(str4));// 1112280004
    }

回归问题:
如果只是单纯的 String str = new String("xyz") ,那么jvm首先会去字符串常量池中查找这个对象,不存在,创建"xyz"这个对象(第一次创建),之后new 关键字会在内从中重新开辟一个新的空间,创建一个新的对象(第二次创建)。

举报

相关推荐

0 条评论