Why are java constants declared static ?
class Foo{ static final int FII = 2 ; }
In this I understand the use of final? Buy why does it have to be static? Why should it be a class variable, and not an instance variable?
Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are stored in the static memory.
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.
We declare methods static so they can be accessed without holding an instance of an Object based on that class.
To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.
If a constant is not static, Java will allocate a memory for that constant in every object of the class (i.e., one copy of the constant per object).
If a constant is static, there will be only one copy of the constant for that class (i.e., one copy per class).
Therefore, if the constant has only one value, it should declared static.
If the constant might have different value for each object, for example the creation time of the object, it should not be declared static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With