When you modify any variable declaration with final, you tell to compiler that once variable is initialized, its value cannot be changed.In other words, any further assignment of value is invalid attempt.
While declaring variable as final , compiler also does some bytecode optimization as you might have guessed they going to have only one value while complete execution of program.
In this post i am going to show initialization of the final member variables. As they declared as the top level variable, so you have options of initializing in various constructs .
Initializing final instance variable
You can initialize the final instance variable in only in the one of following constructs.
- Initializer expression
Its value is initialized while declaration, by evaluating its expression on right hand side as shown in following code snippet - Instance initializer block
You can assign a variable a value in its instance initializer block as shown in following code snippet - Constructor block
Finally in the constructor block as shown in following code snippet
Initializing final static variable
When declare static member variable as final then in following constructs, you can initialize
- Initializer expression
While declaring variable, you can initialize value evaluated in initializer expression as shown following code snippet - Static initializer block
The variable can be initialized in static initializer block. Following code snippet shows initialization.While initializing this final variable make sure that you are initializing only in one of the constructs, otherwise compiler throw an error.
may be i am out of the context, but i would like to know, which one will get first initialized out of these two:
1. the one in instance initializer block or
2. the one in constructor ?
The code inside the constructor look like this
constr-declaration{
super-constr invocation
or
other overloaded constr in same class;
instance initializer blocks to be invoked and are invoked in from their declaration top to bottom ;
constr body ;
}
Therefore, first code in instance initializer block gets executed then constr body.
also final is used for creating constants. like mentioned above,
final member variables have to be definitely initialized at the end of constructor calls.