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

前端 未结 23 2461

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:35

    when they say to write

    String s = "Silly";
    

    instead of

    String s = new String("Silly");
    

    they mean it when creating a String object because both of the above statements create a String object but the new String() version creates two String objects: one in heap and the other in string constant pool. Hence using more memory.

    But when you write

    CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
    

    you are not creating a String instead you are creating an object of class CaseInsensitiveString. Hence you need to use the new operator.

提交回复
热议问题