In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
What's better? And why?
In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
What's better? And why?
very little, and static
There isn't much difference as they are both constants. For most class data objects, static would mean something associated with the class itself, there being only one copy no matter how many objects were created with new.
Since it is a constant, it may not actually be stored in either the class or in an instance, but the compiler still isn't going to let you access instance objects from a static method, even if it knows what they would be. The existence of the reflection API may also require some pointless work if you don't make it static.
From the tests i have made, static final variables are not the same with final(non-static) variables! Final(non-static) variables can differ from object to object!!! But that's only if the initialization is made within the constructor! (If it is not initialized from the constructor then it is only a waste of memory as it creates final variables for every object that is created that cannot be altered.)
For example:
What shows up on screen is:
About Object: A@addbf1 Final: 14 Static Final: 5
About Object: A@530daa Final: 21 Static Final: 5
Anonymous 1st year IT student, Greece