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 .
final means the variable may not be reassigned to another object/primitive.
static means that all code running in the JVM shares the same variable. It exists once per class, instead of once per object.
A final non-static variable can not be reassigned, but each instance has its own copy.
static final fields (accessible without creating an instance) are generally called "Constants"
final (non static) instance variables are generally called "Immutable fields"
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
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