Java Strings: “String s = new String(”silly“);”

前端 未结 23 2816

I\'m a C++ guy learning Java. I\'m reading Effective Java and something confused me. It says never to write code like this:

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


        
23条回答
  •  误落风尘
    2020-11-22 14:28

    The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by

    String s = "Hello";
    

    will only create a string object in the pool and the reference s will refer to it, but by using

    String s = new String("Hello");
    

    you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.

提交回复
热议问题