I was just studying about final data members and i thought what would be the difference final variables vs static final variables ??
I understand that a field that is both static and final has only one piece of storage, and final variable will have storages associated with every instance.
But even if i declare a variable only final, then it remains the same for all the objects as i need to initialize them in the program itself and not at the run time.
So, basically there is no difference between the two except for the memory related issue ??
But even if i declare a variable only final, then it remains the same for all the objects as i need to initialize them in the program itself and not at the run time.
No, non-static final members can be initialized in the constructor. They cannot be re-assigned after that.
The final
means you can assign only one time the value to the variable. The final
can be use in many scopes and is very useful, in a object property you must (and forced) to set the value on the declaration, or in the constructor or in the initialization block of the object.
And the static
is to set the scope of the variable, that means in a class property that value is storage inside the class, and can be access even without an object, when you use static final
or final static
you must (and forced) to set the value on the declaration or inside a static initialization code of the class.
Example:
public class NewClass {
static final int sc = 123; //I recommend to use this declaration style.
final static int scc;
final int o = 123;
final int oo;
final int ooo;
static {
scc = 123;
}
{
oo = 123;
}
public NewClass() {
ooo = 123;
}
void method(final int p) {
// p=123; //Error, the value is only assigned at the call of the method.
final int m = 123;
final int mm;
mm = 123;
// mm = 456; //Error, you can set the value only once.
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(m + p); //You still can reach the variables.
}
}).start();
}
}
final variables : A variable declared final will be a constant, its value can not be changed, and can be initialized in the constructor.
static final variable : This must be initialized, either during the declaration or in the static initializer block.
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