Ok, this question is an extension of this question
Java Strings: "String s = new String("silly");"
The above question asked the same question as this one, but I have a new doubting point.
According to Effective Java
and the answers of above question, we should not do String s = new String("a new string");
, because that will create unnecessary object.
I am not sure about this conclusion, because I think Java is doing automatic string interning, which means for a string, anyway there is only one copy of it in the memory.
So let's see String s = new String("a new string");
.
"a new string"
is already a string which has been created in the memory.
When I do String s = new String("a new string");
, then the s
is also "a new string"
. So according to automatic string interning
, s
should be pointed to the same memory address of "a new string"
, right?
Then how can we say we create unnecessary objects?
new String(...)
. Don't do it unless you have to. – Toxoidintern
ing is only automatically performed onString
literals. – Goodtemperednew
does. – Bocknew String("a new string")
is better than"a new string"
? I can't understand why you want to use the former. – Attainmentwe should NOT do that
is true or not. Also, ifnew string("a string")
is so bad, why doesn't Java simply remove this constructor? – British