Why is there no String.Empty in Java?
Use org.apache.commons.lang.StringUtils.EMPTY
If you want to compare with empty string without worrying about null values you can do the following.
if ("".equals(text))
Ultimately you should do what what you believe is clearest. Most programmers assume "" means empty string, not a string someone forgot to put anything into.
If you think there is a performance advantage, you should test it. If you don't think its worth testing for yourself, its a good indication it really isn't worth it.
It sounds like to you try to solve a problem which was solved when the language was designed more than 15 years ago.
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.