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

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

    If new String() creates 2 objects (one in heap and one in String pool) then what is the use of .intern method ?

    intern() method invoked on a String object looks for the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

提交回复
热议问题