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

后端 未结 9 1187
迷失自我
迷失自我 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:01

    Generally, this indicates someone who isn't comfortable with the new-fashioned C++ style of declaring when initialized.

    Back in the C days, it wasn't considered good form to define auto variables in an inner scope; C++ eliminated the parser restriction, and Java extended that.

    So you see code that has

    int q;
    for(q=0;q

    In the extreme case, all the declarations may be at the top of a function, and not in enclosed scopes like the for loop here.

    IN general, though, the effect of this is to cause a String ctor to be called once, and the resulting String thrown away. (The desire to avoid this is just what led Stroustrup to allow declarations anywhere in the code.) So you are correct that it's unnecessary and bad style at best, and possibly actually bad.

提交回复
热议问题