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 in
String.EMPTY
is 12 characters, and ""
is two, and they would both be referencing exactly the same instance in memory at runtime. I'm not entirely sure why String.EMPTY
would save on compile time, in fact I think it would be the latter.
Especially considering String
s are immutable, it's not like you can first get an empty String, and perform some operations on it - best to use a StringBuilder
(or StringBuffer
if you want to be thread-safe) and turn that into a String.
Update
From your comment to the question:
What inspired this is actually
TextBox.setText("");
I believe it would be totally legitimate to provide a constant in your appropriate class:
private static final String EMPTY_STRING = "";
And then reference it as in your code as
TextBox.setText(EMPTY_STRING);
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.
I understand that every time I type the String literal "", the same String object is referenced in the String pool.
There's no such guarantee made. And you can't rely on it in your application, it's completely up to jvm to decide.
or did the language creators simply not share my views?
Yep. To me, it seems very low priority thing.
Apache StringUtils addresses this problem too.
Failings of the other options:
Granted StringUtils is another library to drag around, but it works very well and saves loads of time and hassle checking for nulls or gracefully handling NPEs.
Use org.apache.commons.lang.StringUtils.EMPTY
All those ""
literals are the same object. Why make all that extra complexity? It's just longer to type and less clear (the cost to the compiler is minimal). Since Java's strings are immutable objects, there's never any need at all to distinguish between them except possibly as an efficiency thing, but with the empty string literal that's not a big deal.
If you really want an EmptyString
constant, make it yourself. But all it will do is encourage even more verbose code; there will never be any benefit to doing so.
To add on to what Noel M stated, you can look at this question, and this answer shows that the constant is reused.
http://forums.java.net/jive/message.jspa?messageID=17122
String constant are always "interned" so there is not really a need for such constant.
String s=""; String t=""; boolean b=s==t; // true