String test=new String("test") 创建的两个对象

发布时间 2023-08-08 11:12:14作者: 民工Bin

String test=new String("test") 会创建几个对象?

上代码

public static void main(String[] args) {

        String test1 = new String("test");
        System.out.println("对象test1的地址");
        System.out.println(System.identityHashCode(test1)); //test1的物理地址hashcode
        System.out.println(System.identityHashCode(test1.intern())); //获取test1在常量池 的对象 的物理地址hashcode

        String test2 = new String("test");
        System.out.println("对象tes2的地址");
        System.out.println(System.identityHashCode(test2));
        System.out.println(System.identityHashCode(test2.intern()));

        String test = "test";
        System.out.println("对象test的地址");
        System.out.println(System.identityHashCode(test));
        System.out.println(System.identityHashCode(test.intern()));

    }

结果:

对象test1的地址
13648335
312116338
对象tes2的地址
453211571
312116338
对象test的地址
312116338
312116338

 

更详细的过程:https://blog.csdn.net/xiaojin21cen/article/details/106404531