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

前端 未结 20 3044
再見小時候
再見小時候 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:29

    Two objects will be created for this:

    String s = new String("abc");
    

    One in the heap and the other in the "string constant pool" (SCP). The reference s will pointing to s always, and GC is not allowed in the SCP area, so all objects on SCP will be destroyed automatically at the time of JVM shutdown.

    For example:

    Here by using a heap object reference we are getting the corresponding SCP object reference by call of intern()

    String s1 = new String("abc");
    String s2 = s1.intern(); // SCP object reference
    System.out.println(s1==s2); // false
    String s3 = "abc";
    System.out.println(s2==s3); //True s3 reference to SCP object here
    

提交回复
热议问题