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
- not worth it–it doesn’t save any space in the heap/stack/string pool,
- ugly
- abuse of a constants class.
Who is the idiot here?
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 😉