What is the purpose of the expression “new String(…)” in Java?

后端 未结 9 1057
迷失自我
迷失自我 2020-11-22 02:39

While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.

For example

9条回答
  •  旧巷少年郎
    2020-11-22 03:00

    Well, that depends on what the "..." is in the example. If it's a StringBuffer, for example, or a byte array, or something, you'll get a String constructed from the data you're passing.

    But if it's just another String, as in new String("Hello World!"), then it should be replaced by simply "Hello World!", in all cases. Strings are immutable, so cloning one serves no purpose -- it's just more verbose and less efficient to create a new String object just to serve as a duplicate of an existing String (whether it be a literal or another String variable you already have).

    In fact, Effective Java (which I highly recommend) uses exactly this as one of its examples of "Avoid creating unnecessary objects":


    As an extreme example of what not to do, consider this statement:

    String s = new String("stringette");  **//DON'T DO THIS!**
    

    (Effective Java, Second Edition)

提交回复
热议问题