16 Jan 2012

A Blank Final Variable

A final variable can only be assigned once in its lifetime. It means they can only be initialized only once. A blank final variable is a one which lacks an initializer.
:



a blank final variable behave differently than instance or static variable. And in this post I'll explore abut how they behave differently and why they do so.


The big statement is The compiler do not assign any default value for a blank final variable. Unlike the instance and static variable who gets default value by the compiler , the blank final do not get any default value.


Compiler Compiler complains on line 13 :  final variable c might  not nave been be initialized  
Therefore a final variable must be explicitly initialized. Initialization can be done either at the time of declaration or any time before using the final variable 


Now the question is how to explicitly initialize a blank final variable.It is also another aspect in which a blank final variable differs from a instance or static variable Lets see how it works
a blank final instance variable can only be initilazed inside the constructor or a instance initializer block but not inside a instance method.
Yes you read right a blank final variable cannot be initilazed inside a instance method.


Have a look


Compiler complains on line 13  cannot assign value to a value to final variable c.


the reason for this is all instance variable must be initilazed by the time object is crested. 


Similarly a blank final  static variable  can only be initilazed into the static initializer block.And yes... yes not inside the static method.This is because by the time class is loaded all static variables must be initialized.


Consider above points before you use a blank final variable next time.So this was all about the blank final variable.

No comments:

Post a Comment