Initializing final member variables in Java

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.
About these ads

3 thoughts on “Initializing final member variables in Java

  1. 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 ?

  2. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s