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?
source to share
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 methodString.intern
.
source to share