Is there a purpose to have a constant for null?

I recently saw something in some code that made me wonder if there was actually some kind of optimization or performance impact. This was the line in the constants file:

public static final Object NULL = null;

      

Then, throughout the code, instead of using the keyword explicitly, null

it will be referenced Constants.NULL

.

I've seen such a thing before with something like:

public static final String EMPTY_STRING = "";

      

... and it seems to make at least some sense if it is an attempt to avoid creating many duplicate instances ""

. But does it really matter with null

, since it isn't really any object? Is there something I am missing?

+3


source to share


3 answers


I don't think defining and using NULL

this way is more than adding noise. Perhaps whoever wrote this code came from a C ++ background and preferred the more familiar NULL

over NULL

.

The second example is also questionable, since using ""

multiple times will not result in a separate object String

created for each use. To quote the JLS :



In addition, the string literal always refers to the same instance of the class String

. This is because string literals - or more generally - strings that are constant expression values ​​(§15.28) - are "interned" to exchange unique instances using a method String.intern

.

+3


source


Nothing makes sense. Using it ""

in multiple places in your code does not create multiple instances of the String object. Unless you explicitly call new String("");

, the JVM just creates a row pool and references one instance of each specific row.



+4


source


Doesn't matter in memory footprint due to the concept of string pooling in java, and also makes the code messier by using the constant NULL instead of null or EMPTY_STRING instead of "".

Both are self-explanatory, so there is no need to create a naming constant for them.

-1


source







All Articles