what happens with new String(“”) in String Constant pool

前端 未结 5 1858
南方客
南方客 2021-01-24 07:05

if i create a string object as

String s=new String(\"Stackoverflow\");

will String object created only in heap, or it also makes a copy in Str

5条回答
  •  深忆病人
    2021-01-24 08:03

    In this case you are constructing an entirely new String object and that object won't be shared in the constant pool. Note though that in order to construct your new String() object you actually passed into it a String constant. That String constant is in the constants pool, however the string you created through new does not point to the same one, even though they have the same value.

    If you did String s = "Stackoverflow" then s would contain a reference to the instance in the pool, also there are methods to let you add Strings to the pool after they have been created.

提交回复
热议问题