Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is making an empty string constant worth it?

Tags:

java

string

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

  1. not worth it--it doesn't save any space in the heap/stack/string pool,
  2. ugly
  3. abuse of a constants class.

Who is the idiot here?

like image 374
jacobko Avatar asked Oct 17 '08 22:10

jacobko


People also ask

Does an empty string have a value?

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 .

Is it better to use or string empty?

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.

Why is string empty not a constant?

Because String is a class and therefore cannot be a constant.

Is string empty equal to?

As mentioned before, a string is empty if its length is equal to zero.


2 Answers

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 ;)

like image 199
Dan Dyer Avatar answered Sep 22 '22 18:09

Dan Dyer


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.

like image 42
Douglas Squirrel Avatar answered Sep 18 '22 18:09

Douglas Squirrel