Reputation: 11592
I recently saw something in some code that made me curious if it was actually having some kind of optimization or performance impact. It was a line like this in a constants file:
public static final Object NULL = null;
Then, throughout the code, rather than explicitly using the null
keyword, it would be referred to with Constants.NULL
.
I've seen this kind of thing before with something like:
public static final String EMPTY_STRING = "";
... and that seemed to make at least a little bit of sense, if it's an attempt to avoid creating lots of duplicate ""
instances. But does it really make any difference with null
, since it's not actually any kind of object? Is there something I'm missing?
Upvotes: 5
Views: 9730
Reputation: 9
There is a purpose to use the Object.NULL.
Suppose that you have a bunch of code that validates if your object is null or not. So as part of a new feature, you need to use default values in some cases of null object.
With the simple if obj != null you can't track down the places where you object is validates against nullity. But if you use obj != Object.NULL then you can use your IDE/editor to help you to find those usages.
Upvotes: -1
Reputation: 575
Does not make any difference in memory occupied due to the string pool concept in java and also it makes the code look more dirty when using NULL constant instead of null or EMPTY_STRING instead of "".
Both of them are self explanatory so there should be no need to create a naming constant for them.
Upvotes: -2
Reputation: 500495
I don't think that defining and using NULL
in this manner does more than add noise. Perhaps whoever wrote that code came from a C++ background, and preferred the more familiar look of NULL
over null
.
The second example is also questionable, since using ""
many times would not result in a separate String
object created for every use. To quote the JLS:
Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
Upvotes: 4
Reputation: 5537
Neither makes any sense. Using ""
in multiple places in your code does not create multiple instances of a String object. Unless you explicitly call new String("");
the JVM just creates a pool of Strings and references the one instance of each particular String.
Upvotes: 5