why are java constants declared static?

Vaibhav picture Vaibhav · Nov 11, 2011 · Viewed 37.8k times · Source

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?

Answer

wannik picture wannik · Nov 11, 2011

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.