Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are java constants declared static?

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?

like image 244
Vaibhav Avatar asked Nov 11 '11 11:11

Vaibhav


People also ask

Are constants static in Java?

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.

Why are instance variables that are declared final usually also declared static?

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.

Why do we declare static?

We declare methods static so they can be accessed without holding an instance of an Object based on that class.

How are constants declared in Java?

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.


1 Answers

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.

like image 144
wannik Avatar answered Oct 19 '22 09:10

wannik