Java – Final vs. Static Variable
The “static” and “final” modifier in Java are somehow confusing, especially when they interact. Here is a good explanation on how to understand these two modifiers:
You DO NOT have to assign a value to a final variable when you declare it. The “final” keyword just means that you can (and must) assign its value exactly once. Where you are allowed to assign the value depends on if it is static or not (as well as its access modifier).
private final int j;
The value MUST be assigned ONCE, either here in the declaration or in each constructor. It is NOT automatically assigned a value of 0 (zero). Also, since it is not static, there is a distinct value for each instance object, so it makes sense that it must be assigned in the constructor.
private static int k;
The value may be assigned from anywhere in this class. Since it is not final, the value may be assigned any number of times, but since it is static, this value is stored at the class-level and universally available to all instances. If left unassigned, it is assumed to be 0 (zero).
private static final int i;
The value MUST be assigned ONCE, either here in the declaration or in a “static” class-level block. It is NOT automatically assigned a value of 0 (zero).
So, to review:
“final”: per-instance value, must be assigned once per instance.
“final” + “static”: per-class value, must be assigned once per class.
“static”: per-class value, can be assigned any number of times per class.
[neither modifier]: per-instance value, can be assigned any number of times per instance.
Before Java can create an instance of a class, it must first load and initialize that class. One step of class initialization is assigning values to all its static fields. If they’re static AND final, those values can’t change once they’re assigned.
Good explanation. Appreciate it.
Very good explanation.
thank you very much….confused lot of times abt this….
but ur explaination cleared every thing….
Thanks for the explanation – very concise and told me exactly what I wanted to know.
Good Explanation
Good explanation…really love it
Thank you! this is a very good explanation!
Thanks for the Explanation. It will be useful for the future coding.
Thanks, this helped clear up the issue for me.
Thanks,its really very helpful.
Help about final method and final class will also
be appriciated