Possible Duplicate:
private final static attribute vs private final attribute
What's the difference between declaring a variable as
static final int x = 5;
or
final int x = 5;
If I only want to the variable to be local, and constant (cannot be changed later)?
Thanks
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
static variable are class variables and its not specific to any instance. Simply we can say its common for all the instance of the class.
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
A static variable is common for all instances of the class. A final variable can not change after it has been set the first time. So a static final variable in Java is common for all instances of the class, and it can not be changed after it has been set the first time.
Just having final
will have the intended effect.
final int x = 5; ... x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.
Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.
As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').
Similar question is private final static attribute vs private final attribute
Hope it helps
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