String s = new String(“xyz”). How many objects has been made after this line of code execute?

前端 未结 20 2991
再見小時候
再見小時候 2020-11-27 02:45

The commonly agreed answer to this interview question is that two objects are created by the code. But I don\'t think so; I wrote some code to confirm.

publi         


        
20条回答
  •  独厮守ぢ
    2020-11-27 03:10

    @Giulio, You are right. String s3 = new String("abc"); creates two objects one in heap with reference s3 and another in SCP(Without reference). and now String s2 = "abc"; doesn't create any new object in SCP because "abc" is already there in SCP.

        String s1 = "abc";
        String s2 = "abc";
        String s3 = new String("abc");
        String s4 = s3.intern();
        System.out.println("s1: "+System.identityHashCode(s1));
        System.out.println("s2: "+System.identityHashCode(s2));
        System.out.println("s3: "+System.identityHashCode(s3));
        System.out.println("s4: "+System.identityHashCode(s4));
    

    O/P:s1: 366712642, s2: 366712642, s3: 1829164700, s4: 366712642

    As i am not eligible for commenting i wrote it here.

提交回复
热议问题