Is making an empty string constant worth it?

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?

Asked by: Victoria313 | Posted: 23-01-2022

Answer 1

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

Answered by: Walter513 | Posted: 24-02-2022

Answer 2

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.


0 == possiblyEmptyString.length()


possiblyEmptyString.isEmpty() // Java 6 only

are just as clear.

Answered by: Miranda554 | Posted: 24-02-2022

Answer 3

I much prefer seeing EMPTY_STRING.

It makes it english. "".equals 'reads' differently than EMPTY_STRING.equals.

Answered by: Cadie681 | Posted: 24-02-2022

Answer 4

Ironically the whole point of constants is to make them easily changeable. So unless your co-worker plans to redefine EMPTY_STRING to be something other than an empty string - which would be a really stupid thing to do - casting a genuine fixed construct such as "" to a constant is a bad thing.

As Dan Dyer says, its like defining the constant ONE to be 1: it is completely pointless and would be utterly confusing - potentially risky - if someone redefined it.

Answered by: Walter603 | Posted: 24-02-2022

Answer 5

Well, I could guess too, but I did a quick test... Almost like cheating...

An arbitrary string is checked using various methods. (several iterations)

The results suggests that isEmpty() is both faster and indeed more readable; If isEmpty() is not available, length() is a good alternative.

Using a constant is probably not worth it.

"".equals(someString())      :24735 ms
t != null && t.equals("")    :23363 ms
t != null && t.equals(EMPTY) :22561 ms
EMPTY.equals(someString())   :22159 ms
t != null && t.length() == 0 :18388 ms
t != null && t.isEmpty()     :18375 ms
someString().length() == 0   :18171 ms

In this scenario;


I would suggest defining a constant in a r e l e v a n t place, since a global class for all constants really sucks. If there is no relevant place, you are probably doing something else wrong...


Might be considered a relevant place where as;

CommonConstants.I__AM__A__LAZY__PROGRAMMER // true

is not.

For BigIntegers and similar thing, I tend to end up defining a final static locally; like:

private final static BigDecimal ZERO = new BigDecimal(0);
private final static BigDecimal B100 = new BigDecimal("100.00");

Thats bugs me and wouldn't it be nice with some sugar for BigInts and BigDecimals...

Answered by: Patrick888 | Posted: 24-02-2022

Answer 6

I'm with your coworker. While the empty string is hard to mistype, you can accidentally put a space in there and it may be difficult to notice when scanning the code. More to the point it is a good practice to do this with all of your string constants that get used in more than one place -- although, I tend to do this at the class level rather than as global constants.

FWIW, C# has a static property string.Empty for just this purpose and I find that it improves the readability of the code immensely.

Answered by: Eric433 | Posted: 24-02-2022

Answer 7

As a tangent to the question, I generally recommend using a utility function when what you're really checking for is "no useful value" rather than, specifically, the empty string. In general, I tend to use:

import org.apache.commons.lang.StringUtils;

// Check if a String is whitespace, empty ("") or null.
// Check if a String is empty ("") or null.

The concept being that the above two:

  • Check the various other cases, including being null safe, and (more importantly)
  • Conveys what you are trying to test, rather than how to test it.

Answered by: Elian459 | Posted: 24-02-2022

Answer 8

David Arno states: -

Ironically the whole point of constants is to make them easily changeable

This is simply not true. The whole point of constants is reuse of the same value and for greater readability.

It is very rare that constant values are changed (hence the name). It is more often that configuration values are changed, but persisted as data somewhere (like a config file or registry entry)

Since early programming, constants have been used to turn things like cryptic hex values such as 0xff6d8da412 into something humanly readable without ever intending to change the values.

const int MODE_READ       = 0x000000FF;
const int MODE_EXECUTE    = 0x00FF0000;
const int MODE_WRITE      = 0x0000FF00;
const int MODE_READ_WRITE = 0x0000FFFF;

Answered by: Brooke132 | Posted: 24-02-2022

Answer 9

I don't like either choice. Why not if (otherString.length() == 0)

Edit: I actually always code

if (otherString == null || otherString.length() == 0)

Answered by: Aida788 | Posted: 24-02-2022

Answer 10

  1. yes--it offers no benefit.
  2. depends on what you're used to, I'm sure.
  3. No, it's just a constant--not an abuse.

Answered by: Wilson892 | Posted: 24-02-2022

Answer 11

The same argument comes up in .NET from time to time (where there's already a readonly static field string.Empty). It's a matter of taste - but personally I find "" less obtrusive.

Answered by: Julian124 | Posted: 24-02-2022

Answer 12

Hehe, funny thing is: Once it compiles, you wont see a difference (in the byte-code) between the "static final" thing and the string literal, as the Java-compiler always inlines "static final String" into the target class. Just change your empty string into something recognizable (like the LGPL-text) and look at the resulting *.class file of code that refernces that constant. You will find your text copied into that class-file.

Answered by: Edgar228 | Posted: 24-02-2022

Answer 13

One case where it does make sense to have a constant with value of empty string is when you the name captures the semantics of the value. For example:

if (Constants.FORM_FIELD_NOT_SET.equals(form.getField("foobar"))) {

This makes the code more self documenting (apart from the argument that a better design is to add the method checking whether a field is set to the form itself).

Answered by: Elise174 | Posted: 24-02-2022

Answer 14

We just do the following for situations like this:

public class StaticUtils
    public static boolean empty(CharSequence cs)
        return cs == null || cs.length() == 0;

    public static boolean has(CharSequence cs)
        return !empty(cs);

Then just import static StaticUtils.*

Answered by: First Name337 | Posted: 24-02-2022

Answer 15

Hmm, the rules are right but are being taken in a different sense! Lets look at the cause, firstly all object references in java are checked by equals(). Earlier on, in some languages it was done using '==' operator, if by accident someone used '=' for '==', a catastrophe. Now the question of magic numbers/constants, for a computer all constants/numbers are similar. Instead of 'int ONE=1' one can surely use 1, but will that hold true for double PI = 3.141...? What happens if someone tries to change the precision sometime later.

If we were to come up with a check list, what would the rule be address the general guideline isn't it? All I mean to say is that rules are supposed to aid, we can surely bend the rules only when we know them very well. Common sense prevails. As suggested by a friend of mine, program constants like 0/1 which denote exit conditions can be hard coded and hence magic number principle doesn't apply. But for those which participate in logical checks/rules, better keep them as configurable constants.

Answered by: Ryan757 | Posted: 24-02-2022

Answer 16

Why it is preferable to use String.Empty in C# and therefore a public constant in other languages, is that constants are static, therefore only take up one instance in memory.

Every time you do something like this: -

stringVariable = "";

you are creating a new instance of a null string, and pointing to it with stringVariable.

So every time you make an assignment of "" to a variable (pointer), that "" null string is a new string instance until it no longer has any pointer assignments to it.

initializing strings by pointing them all to the same constant, means only one "" is ever created and every initialized variable points to the same null string.

It may sound trivial, but creating and destroying strings is much more resource intensive than creating pointers (variables) and pointing them to an existing string.

As string initialization is common, it is good practice to do: -

const String EMPTY_STRING = "";
String variable1 = EMPTY_STRING;
String variable2 = EMPTY_STRING;
String variable3 = EMPTY_STRING;
String variable4 = EMPTY_STRING;
String variable5 = EMPTY_STRING;

You have created 5 string pointers but only 1 string

rather than: -

String variable1 = "";
String variable2 = "";
String variable3 = "";
String variable4 = "";
String variable5 = "";

You have created 5 string pointers and 5 separate null strings.

Not a major issue in this case, but in thousands of lines of code in dozens of classes, it is unnecessary memory waste and processor use, creating another null string variable, when they can all point to the same one, making applications much more efficient.

Of course, compilers should be clever enough to determine several static strings and reuse duplicates, but why assume?

Also, it's less prone to introducing errors as "" and " " will both compile, yet you may miss the space you accidentally added which could produce spurious run time errors, for example conditional logic such as: -

myvariable = " ";
While (myVariable == ""){

Code inside the while block is unreachable because myVariable will not satisfy the condition on the first iteration. The error of initializing with " " instead of "" is easy to miss, whereas: -

myvariable = EMPTY_STRING;
While (myVariable == EMPTY_STRING){

... is less likely to cause runtime errors, especially as misspelling EMPTY_STRING would generate a compile error instead of having to catch the error at run time.

The cleanest solution, would be to create a static class that contains members of all kinds of string constants you need, should you require more than just an empty string.

public static class StringConstants{
    public static String Empty = "";
    public static String EMail = "mailto:%s";
    public static String http = "http://%s";
    public static String https = "https://%s";
    public static String LogEntry = "TimeStamp:%tYmdHMSL | LogLevel:%s| Type:%s | Message: '%s'";


String myVariable = StringConstants.Empty;

You may even be able to extend the native String object, depending on your language.

Answered by: Kate256 | Posted: 24-02-2022

Answer 17

If you every wish to store "empty" strings in a nullable string column in oracle, you will have to change the definition of EMPTY_STRING to be something other than ""! (I recall from the last time I was forced to use Oracle that it does not know the difference between an empty string and a null string).

However this should be done in your data access layer so the rest of the app does not know about it, and/or sort out your data model so you don’t need to store empty string AND null strings in the same column.

Answered by: Ned566 | Posted: 24-02-2022

Answer 18

Or simply just have it as string.IsNullOrEmpty(otherString)

Answered by: Darcy668 | Posted: 24-02-2022

Similar questions

syntax - In Java, can I define an integer constant in binary format?

Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?

Is possible to get a constant value declared in a database package? (SQL or Java)

I have some Packages in a Oracle database. They contain stored procedures, functions and constants. I can call functions, in Java, using a Java CallableStatement. Also, I could execute a SQL statement as "select package1.function1(value1) from dual;". But I can't find how to get the value of a constant declared in the package, in Java. For example: PACKAGE Package1 AS A_CONSTANT CONSTANT VARCHAR...

java - Is constant polling in RXTX necessary?

While trying to figure out this problem (any help there is appreciated), I ran RXTX while monitoring its activity using PortMon and noticed that RXTX constantly checks if data is available, even when the Java client reads from the

How do I create a constant object in Java?

How do I create a reference to a constant object? final Myclass obj = new Myclass(); does not work, it says obj(the reference) should not be re-assigned but we can still change the object referred. I want to ensure that the object itself does not change once constructed.

core - What is constant folding in java compiler?

This question already has answers here:

java - How should I declare a constant set visible for every instance of the class?

I would like to have a constant set in my class which would be visible for all instances of the class. First, I do not know if I need to declare it as "static". As far as I understand any changes of a static field (done by one of the instances) will be seen by other instances (so static variable is not bound to a specific instance). Moreover, a static field can be changes without usage of any instance (we work dire...

Java "constant string too long" compile error. Only happens using Ant, not when using Eclipse

I have a few really long strings in one class for initializing user information. When I compile in Eclipse, I don't get any errors or warnings, and the resulting .jar runs fine. Recently, I decided to create an ant build file to use. Whenever I compile the same class with ant, I get the "constant string too long" compile error. I've tried a number of ways to set the java compiler executable in ant to make sure that...

Why is there no Constant feature in Java?

I was trying to identify the reason behind constants in Java I have learned that Java allows us to declare constants by using final keyword. My question is why didn't Java introduce a Constant (const) feature. Since many people say it has come from C++, in C++ we have const keyword. Please share your thoughts.

java - Enum and Generic constant specific method

I have an enum like: enum TEST { TEST1, TEST 2; public abstract <T> String stringify (T input); } I need to add a constant specific method , something like stringify. This method will take different types of inputs (for each enum). Can I do that? Eclipse is not letting me do it ..something like: enum TEST { TEST1( public &lt...

java - String constant versus variable

What's the difference between a string constant and a string variable?

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)