I have a co-worker that swears by
//in a singleton "Constants" class public static final String EMPTY_STRING = "";
in a constants class available throughout the project. That way, we can write something like
if (Constants.EMPTY_STRING.equals(otherString)) { ... }
instead of
if ("".equals(otherString)) { ... }
I say it's
Who is the idiot here?
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
Generally, using String. Empty will serve you better than using “”. In the cases where String. Empty will not work either because of the code evaluation OR because of the performance considerations, yes, use “” instead.
Because String is a class and therefore cannot be a constant.
As mentioned before, a string is empty if its length is equal to zero.
String literals are interned by default, so no matter how many times you refer to "" in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.
Of course, if you want to change the value of EMPTY_STRING later, it's handy to have it in one place ;)
Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.
Either
0 == possiblyEmptyString.length()
or
possiblyEmptyString.isEmpty() // Java 6 only
are just as clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With