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

前端 未结 23 2809

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

    In Java the syntax "text" creates an instance of class java.lang.String. The assignment:

    String foo = "text";
    

    is a simple assignment, with no copy constructor necessary.

    MyString bar = "text";
    

    Is illegal whatever you do because the MyString class isn't either java.lang.String or a superclass of java.lang.String.

提交回复
热议问题