I understand that every time I type the string literal "", the same String object is referenced in the string pool.
But why doesn’t the String API include a public static final String Empty = "";, so I could use references to String.Empty?
It would save on compile time, at the very least, since the compiler would know to reference the existing String, and not have to check if it had already been created for reuse, right? And personally I think a proliferation of string literals, especially tiny ones, in many cases is a “code smell”.
So was there a Grand Design Reason behind no String.Empty, or did the language creators simply not share my views?
String.EMPTYis 12 characters, and""is two, and they would both be referencing exactly the same instance in memory at runtime. I’m not entirely sure whyString.EMPTYwould save on compile time, in fact I think it would be the latter.Especially considering
Strings are immutable, it’s not like you can first get an empty String, and perform some operations on it – best to use aStringBuilder(orStringBufferif you want to be thread-safe) and turn that into a String.Update
From your comment to the question:
I believe it would be totally legitimate to provide a constant in your appropriate class:
And then reference it as in your code as
As this way at least you are explicit that you want an empty String, rather than you forgot to fill in the String in your IDE or something similar.