Search code examples
javaconstants

constant data member


when we use final keyword that variable has been declared as constant then what is the necessity of using static ? I have seen in most of the places that we use

public static final int nVar = 12

for constant data member .


Solution

  • final means that, once assigned the value of variable cannot be modified.

    static means "associated with the class"; without it, the variable is associated with each instance of the class. if not, you'll have one for each instance you create. static means the variable will remain in memory for as long as the class is loaded

    There is no point in declaring a variable like this.

    public final int nVar = 12;
    

    If this is not meant to be modified, why have one copy per instance.

    Hence, Class constants need to be declared as static final where as the variables which you want to be immutable on per instance basis, you declare them as final