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

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

    If we execute String s = new String("Brajesh"); , two objects shall be created. One object will be created in string literal pool and another one in heap area. But if we have already same string literal object, then only one object is created. like

    String s1  ="Brajesh"; 
    String s = new String("Brajesh");//it will create only one object in heap area
    

    Apart from this one additional object is also created in heap area that is char[]'s object. I have attached here snapshot of heap memory.

提交回复
热议问题