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

前端 未结 23 2937

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条回答
  •  猫巷女王i
    2020-11-22 14:43

    Java creates a String object for each string literal you use in your code. Any time "" is used, it is the same as calling new String().

    Strings are complex data that just "act" like primitive data. String literals are actually objects even though we pretend they're primitive literals, like 6, 6.0, 'c', etc. So the String "literal" "text" returns a new String object with value char[] value = {'t','e','x','t}. Therefore, calling

    new String("text"); 
    

    is actually akin to calling

    new String(new String(new char[]{'t','e','x','t'}));
    

    Hopefully from here, you can see why your textbook considers this redundant.

    For reference, here is the implementation of String: http://www.docjar.com/html/api/java/lang/String.java.html

    It's a fun read and might inspire some insight. It's also great for beginners to read and try to understand, as the code demonstrates very professional and convention-compliant code.

    Another good reference is the Java tutorial on Strings: http://docs.oracle.com/javase/tutorial/java/data/strings.html

提交回复
热议问题