I know that:
A blank final class variable must be definitely assigned by a static initializer of the class in which it is declared, or a compile-time error occurs.
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared, or a compile-time error occurs.
Why final variable cannot be assigned just once at any time instead of just at declare time?
The corollary to this, for non-final
variables, is the initial value of a variable. Every field receives an initial value depending on its type - usually a variant of 0
or null
.
It's implied here that, if you're declaring a variable to be final
, then you have a specific value in mind that you wish that variable to be assigned and not have changed later in its run. Java doesn't know what value that is, and it likely takes away the convenience of automatically declaring those values for you so to not interfere with the developer's intentions.
That and requiring that all final
variables be initialized is to support all variables being definitely assigned before their use. You can use a non-final
field that you don't initialize to some value - it'll likely be null
though - but you can't use a local variable that you haven't initialized yet for the same reason.